2016-11-21 57 views
1

我在檢索具有名稱空間的XML源的標記值時遇到了一些問題。使用PHP中的名稱空間檢索XML內容中的值數組

我已閱讀並試圖執行一些以前的問題所推薦的答案,但我仍然得到一個空數組,或像

Warning: SimpleXMLElement::xpath() [simplexmlelement.xpath]: Undefined namespace prefix 

警告我讀Parse XML with Namespace using SimpleXML

的XML提要數據是這樣的:

<Session> 
     <AreComplimentariesAllowed>true</AreComplimentariesAllowed> 
     <Attributes xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"> 
     <d3p1:string>0000000009</d3p1:string> 
     <d3p1:string>0000000011</d3p1:string> 
     </Attributes> 
</Session> 

我當前的代碼:

foreach($xml->Session as $event){ 
    if(!empty($event->Attributes)){ 
     foreach($event->xpath('//Attributes:d3p1') as $atts) { 
      echo $atts."<br />"; 
     } 
    } 
} 

任何指導,將不勝感激。

謝謝。

回答

1

您需要註冊命名空間:

foreach ($xml->xpath('//Attributes') as $attr) { 
    $attr->registerXPathNamespace('ns', 
    'http://schemas.microsoft.com/2003/10/Serialization/Arrays'); 
    foreach ($attr->xpath('//ns:string') as $string) { 
    echo $string, PHP_EOL; 
    } 
} 

在情況下,如果你想獲取的string標籤只值:

$xml->registerXPathNamespace('ns', 
    'http://schemas.microsoft.com/2003/10/Serialization/Arrays'); 
foreach ($xml->xpath('//Attributes/ns:string') as $string) { 
    echo $string, PHP_EOL; 
} 
+0

感謝這些。他們中沒有一個能夠工作,但那是因爲命名空間中的鏈接現在已經死了? http://schemas.microsoft.com/2003/10/Serialization/Arrays – David

+0

@David,實際上這兩個示例的工作,如果你正確加載'$ xml'。 [示例](https://eval.in/682071) –

+0

最初我使用cURL來獲取XML數據(curl_setopt($ ch,CURLOPT_HTTPHEADER,array('Accept:application/xml')),然後使用以下命令加載:$ xml = new SimpleXMLElement(str_replace(「&」,「&」,$ data)); – David