我正在使用以下代码向SOAP服务发送请求:
header('Content-type: application/xml');
function doXMLCurl($url,$postXML){
$CURL = curl_init();
curl_setopt($CURL, CURLOPT_URL, $url);
curl_setopt($CURL, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($CURL, CURLOPT_POST, 1);
curl_setopt($CURL, CURLOPT_POSTFIELDS, $postXML);
curl_setopt($CURL, CURLOPT_HEADER, false);
curl_setopt($CURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($CURL, CURLOPT_HTTPHEADER, array('Accept: text/xml','Content-Type: application/soap+xml'));
curl_setopt($CURL, CURLOPT_RETURNTRANSFER, true);
$xmlResponse = curl_exec($CURL);
return $xmlResponse;
}
$input_xml = '<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">.....</s:Envelope>';
echo doXMLCurl('webservice_url', $input_xml);
响应也是XML。
如何解析此数据或转换为数组或对象?我尝试使用 simplexml_load_string(),但没有成功。
修改
XML响应:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">...</a:Action>
</s:Header>
<s:Body>
<ListStatesResponse xmlns="http://tempuri.org/">
<ListStatesResult xmlns:b="..." xmlns:i="...">
<b:Return>0</b:Return>
<b:Message i:nil="true"/>
<b:Status>00</b:Status>
<b:ListStates>
<b:States>
<b:Description>ACRE</b:Description>
<b:Code>AC</b:Code>
</b:States>
<b:States>
<b:Description>ALAGOAS</b:Description>
<b:Code>AL</b:Code>
</b:States>
<b:States>
<b:Description>AMAZONAS</b:Description>
<b:Code>AM</b:Code>
</b:States>
...
</b:ListStates>
</ListStatesResult>
</ListStatesResponse>
</s:Body>
</s:Envelope>
答案 0 :(得分:0)
我发现最简单的方法是使用json函数
$jsonObject = json_decode(json_encode($xmlString));
然后print_r($jsonObject)
找到结构。这允许使用$jsonObject->{'@attributes'}->id;
答案 1 :(得分:0)
假设xml
有效,您可以使用SimpleXMLElement,即:
$xml = new SimpleXMLElement($xmlResponse);
echo $xml->node->otherNode['Id'];
要循环播放,请使用:
foreach ($xml->node->otherNode as $el) {
foreach($el as $key => $val) {
echo "{$key}: {$val}";
}
}