2010-10-22 74 views
5
<?xml version="1.0" encoding="UTF-8"?> 
    <answer> 
    <describe data="aircompany"> 
     <data> 
     <code xml:lang="ru">FW</code> 
     <code xml:lang="en">FW</code> 
     </data> 
     <data> 
     <code xml:lang="ru">UT</code> 
     <code xml:lang="en">ЮТ</code> 
     </data> 
    </describe> 
    </answer> 

我需要獲取節點值,那裏是xml:lang =「en」。如何在PHP中做到這一點?xml:lang在PHP中解析

回答

4

是,SimpleXML的作品,但嘗試添加xml namespace如果你遇到麻煩。

例如爲:

<?php 
$xmlstr = <<<XML 
<?xml version="1.0" encoding="UTF-8"?> 
<answer xmlns:xml="http://www.w3.org/XML/1998/namespace"> 
    <describe data="aircompany"> 
     <data> 
     <code xml:lang="ru">ФВ</code> 
     <code xml:lang="en">FW</code> 
     </data> 
     <data> 
     <code xml:lang="ru">УТ</code> 
     <code xml:lang="en">UT</code> 
     </data> 
    </describe> 
</answer> 
XML; 

$xml = new SimpleXMLElement($xmlstr); 

foreach ($xml->xpath('//data/code[@xml:lang="en"]') as $code) { 
    echo $code, '<br/>', PHP_EOL; 
} 
?> 
1

之前曾去過回答:

$dom =new DOMDocument; 
$dom->loadXML($xml); 
$xPath = new DOMXPath($dom); 
$nodes = $xPath->query('/answer/describe/data/code[@xml:lang = "en"]'); 
foreach($nodes as $node) { 
    echo $node->nodeValue; 
} 

替代而不使用XPath:

$dom =new DOMDocument; 
$dom->loadXML ($xml); 
foreach($dom->getElementsByTagName('code') as $node) { 
    if($node->getAttribute('xml:lang') === 'en') { 
     echo $node->nodeValue; 
    } 
} 
1

感謝。 我用這個方法:

$XMLObj = new SimpleXMLElement($XML); 
print_r($XMLObj->xpath('/answer/describe/data/code[@xml:lang = "en"]')); 
+0

好東西。歡迎加入:) – Oleg 2010-10-22 12:13:40

5

的XPath有處理XML的一種特殊構造:lang屬性:

$xml = new SimpleXMLElement($strXML); 
$data = $xml->describe->data[0]; 
$elCode = $data->xpath("code[lang('en')]"); // returns array of SimpleXMLElement 
assert(count($elCode)==1); 
$code_en = (string) $elCode[0]; 

附:向Sirena問候;)