【发布时间】:2014-03-28 12:24:25
【问题描述】:
我正在尝试解析以下 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>
我通过 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);
我对所有这些都是新手,所以请原谅明显的错误,但我随后尝试将响应作为对象进行迭代,由 simpleXML 扩展名解析,引用 SO 答案 here 并使用 @987654322 @plugin 来回显对象内容。
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 扩展提供的文档。我宁愿使用“基本”代码来实现我所需要的。
【问题讨论】: