我正在尝试解析以下 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>
Run Code Online (Sandbox Code Playgroud)
我通过 cURL 检索响应:
$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);
Run Code Online (Sandbox Code Playgroud)
我是这一切的新手,所以请原谅明显的错误,但我随后尝试将响应作为对象进行迭代,正如 simpleXML 扩展所解析的那样,在此处引用 SO 答案并使用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;
}
Run Code Online (Sandbox Code Playgroud)
这给了我以下内容:
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
}
]
Run Code Online (Sandbox Code Playgroud)
我想进入可以使用foreach循环或仅直接指向相关数据 ( $title = (string)$data->title;)遍历 XML 文档正文的阶段。我怎样才能从我目前的位置前进到那个阶段?我真的不知道接下来会发生什么,而且我完全不了解为 PHP 中的 SOAP 扩展提供的文档。我宁愿使用“基本”代码来实现我所需要的。
适应您的问题:
$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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18407 次 |
| 最近记录: |