2014-03-28 154 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