2014-03-28 177 views
0

我試圖解析以下SOAP響應,而且需要一些指導:PHP解析SOAP響應

<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"> 
    <env:Header/> 

    <env:Body> 
     <ns2:LookupResponse xmlns:ns2="http://path-to/schemas"> 
     <ns2:Name>My Name</ns2:Name> 
     <ns2:Address1>test</ns2:Address1> 
     <ns2:Address2>test</ns2:Address2> 
     ... 
     </ns2:LookupResponse> 
    </env:Body> 
</env:Envelope> 

我retreive通過捲曲的響應:

$url  = 'https://path-to-service'; 
$success = FALSE; 
$ch   = curl_init(); 

curl_setopt($ch, CURLOPT_URL,   $url);                 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 
curl_setopt($ch, CURLOPT_SSLVERSION,  3); 
curl_setopt($ch, CURLOPT_POST,   true); 
curl_setopt($ch, CURLOPT_POSTFIELDS,  $request); 
curl_setopt($ch, CURLOPT_HTTPHEADER,  array(
                'Content-Type: text/xml; charset=utf-8', 
                'Content-Length: ' . strlen($request) 
               )); 

$ch_result = curl_exec($ch); 
$ch_error = curl_error($ch); 

curl_close($ch); 

我是新來的所有這樣,原諒明顯的錯誤,但我然後嘗試迭代通過作爲對象的響應,由simpleXML擴展分析,引用SO回答here和使用simplexml_debug插件回顯對象內容。

if(empty($ch_error)) 
{ 
    $xml = simplexml_load_string($ch_result, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/"); 
    $xml ->registerXPathNamespace('env', 'http://schemas.xmlsoap.org/soap/envelope/'); 
    $xml ->registerXPathNamespace('ns2', 'http://path-to/schemas'); 


    echo '<pre>'; 
    simplexml_dump($xml); 
    echo '</pre>'; 

} 
else 
{ 
    echo 'error'; 
    show($ch_error); 
    exit; 
} 

這使我有以下幾點:

SimpleXML object (1 item) 
[ 
Element { 
    Namespace: 'http://schemas.xmlsoap.org/soap/envelope/' 
    Namespace Alias: 'env' 
    Name: 'Envelope' 
    String Content: '' 
    Content in Namespace env 
     Namespace URI: 'http://schemas.xmlsoap.org/soap/envelope/' 
     Children: 2 - 1 'Body', 1 'Header' 
     Attributes: 0 
} 
] 

我想要去的地方,我可以通過XML文檔的主體迭代算法,使用foreach環,或者僅僅是直接指向階段相關數據($title = (string)$data->title;)。我如何從現在的位置走到那個階段?我真的不知道接下來會發生什麼,我只是不明白在PHP中爲SOAP擴展提供的文檔。我寧願使用'基本'代碼來實現我所需要的。

回答

3

This topic should help you solving your problem.

適應於您的問題:

$xml = simplexml_load_string($ch_result, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/"); 
$ns = $xml->getNamespaces(true); 
$soap = $xml->children($ns['env']); 
$res = $soap->Body->children($ns['ns2']); 

foreach ($res->LookupResponse as $item) { 
    echo $item->Name.PHP_EOL; 
} 
+0

感謝您的參考。試試這個(使用相同的代碼):'$ xml = simplexml_load_string($ ch_result); $ ns = $ xml-> getNamespaces(true); $ envelope = $ xml-> children($ ns ['env']); $ body = $ envelope-> body-> children($ ns ['ns2']); echo $ body-> Name;'returns'警告:main():節點不再存在。很明顯,我錯過了某個步驟(儘管邏輯對我而言變得清晰)... – Eamonn

+2

'$ body'包含'LookupResponse'的父項,因此您必須遍歷它們以獲取所有考慮的名稱!你可以這樣做:'foreach($ body-> LookupResponse as $ item){echo $ item-> Name.PHP_EOL; }'。對於你的元素的情況也是**非常謹慎:身體<>身體!所以你必須寫:'$ body = $ envelope-> Body-> children($ ns ['ns2']);'。 – Tyrael

+0

啊我明白了。謝謝! – Eamonn