2013-04-01 90 views
1

得到節點我有xml文件:的SimpleXML通過屬性

<?xml version="1.0" ?> 
<xml> 
<opis lang="en">My text</opis> 
<opis lang="cz">My text2</opis> 
</xml> 

我想 「我的文本2」 - 這樣一個節點,在屬性lang是 「CZ」:

$xml = simplexml_load_file($fileName); 
$result = $xml->xpath('//xml/opis[@lang="cz"]') 

但代替的價值,我得到:

array(1) (
    [0] => SimpleXMLElement object { 
    @attributes => array(1) (
     [lang] => (string) cz 
    ) 
    } 
)) 
+0

的可能重複[SimpleXML的:選擇具有一定屬性值的元素(http://stackoverflow.com/questions/992450/simplexml-selecting-元素,它具有一定的屬性值) – hakre

回答

0

使用try的DomDocument:

$xml = new DomDocument; 
$xml->load('yourFile'); 
$xpath = new DomXpath($xml); 

foreach ($xpath->query('//xml/opis[@lang="cz"]') as $rowNode) { 
    echo $rowNode->nodeValue; // will be 'this item' 
} 
+0

謝謝!就是這個! – wioskamala

+0

@wioskamala很好地幫助您 – alwaysLearn

+1

-1:OP要求提供SimpleXML,它可以同樣地執行(如果不是更簡單的話)。還有 - SimpleXML或DOMDocument - 重複。 – hakre

1

你可以得到這樣的價值:

$xml = simplexml_load_file($fileName); 
$result = $xml->xpath('//xml/opis[@lang="cz"]'); 
foreach($result as $res) { 
    echo $res; 
}