2011-06-23 86 views
1

所有,的SimpleXML解析問題

試圖解析這個SOAP響應,但XPath的()將返回

調試警告:的SimpleXMLElement :: XPath的()未定義命名空間前綴 調試警告:的SimpleXMLElement :: XPath的()評估失敗

$result = '<?xml version="1.0" encoding="UTF-8"?> 
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> 
    <env:Header xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"/> 
    <env:Body xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> 
     <v4:TrackReply xmlns:v4="http://fedex.com/ws/track/v4"> 
      ... 
     </v4:TrackReply> 
    </env:Body> 
</soapenv:Envelope>'; 


$xml = simplexml_load_string($result,NULL,NULL,'http://schemas.xmlsoap.org/soap/envelope/'); 



foreach($xml->xpath('env:Body') as $body){ 

    //drill down here... 
} 

回答

2

嘗試內body

$bodies = $xml->xpath('env:Body'); 
foreach($bodies as $body){ 
    $reply = $body->children('v4', TRUE)->TrackReply; 
    var_dump($reply); 
} 

或者註冊的命名空間爲 'ENV'

$xml->registerXPathNamespace('env', 'http://schemas.xmlsoap.org/soap/envelope/');

編輯 此代碼設置子元素的命名空間,你可以得到這樣一個元素TrackReply直接與:

$xml->registerXPathNamespace('env', 'http://schemas.xmlsoap.org/soap/envelope/'); 
$xml->registerXPathNamespace('v4', 'http://fedex.com/ws/track/v4'); 
var_dump($xml->xpath('env:Body/v4:TrackReply')); 
+0

通過調用registerXPathNamespace()我能夠進入我的foreach循環,因爲$ xml-> xpath('env:Body')現在創建一個空的SimpleXMLElement對象 – Slinky

+0

@Slinky查看更新的答案 - SimpleXMLElement對象看起來是空的,但實際上包含我看到的信息 –

+0

。這有助於很多。謝謝 – Slinky

-1

的SimpleXML忽略的XML結構的env:部分和代替返回這樣構造的對象:

SimpleXMLElement Object 
(
    [Header] => SimpleXMLElement Object 
     (
     ) 

    [Body] => SimpleXMLElement Object 
     (
     ) 

) 

您可以使用以下XPath查詢訪問正文:$xml->xpath('Body')或僅使用以下語法訪問子項:$xml->Body