如何解析对PHP的XML响应?我尝试了几种解决方案但没有任何效果。这是我得到的XML:
<soapenv:envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:body>
<ns:getrateresponse xmlns:ns="http://services.gts">
<ns:return xmlns:ax25="http://services.gts/xsd" xmlns:ax26="http://model.gts/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax25:RaterResponseAutoQuotes">
<ax25:carriers xsi:type="ax25:RaterResponseCarriersAutoQuotes">
<ax25:accessorials xsi:type="ax25:RaterResponseAccessorial">
<ax25:aramount>12.66</ax25:aramount>
<ax25:accessorialid>22</ax25:accessorialid>
<ax25:accessorialname>Fuel</ax25:accessorialname>
</ax25:accessorials>
<ax25:ar_final_rate>161.66</ax25:ar_final_rate>
<ax25:carrier_id>0000087</ax25:carrier_id>
<ax25:carrier_name>CON-WAY FREIGHT INC</ax25:carrier_name>
<ax25:service_days>04</ax25:service_days>
</ax25:carriers>
<ax25:message>Success</ax25:message>
<ax25:referencenumber>3184877</ax25:referencenumber>
<ax25:success>true</ax25:success>
</ns:return>
</ns:getrateresponse>
</soapenv:body>
解析:
foreach($xml->ax25:carriers as $carrier) {
$$carrierObject = array(
"rate" => $carrier->ar_final_rate,
);
array_push($carriers, $$carrierObject);
}
我所关心的只是每个ax25:carriers
ax25:ar_final_rate
。我也试过
$result = new SimpleXMLElement($response);
但是回来
object(SimpleXMLElement)#2 (0) { }
答案 0 :(得分:0)
我们正在使用DOMDocument
在这些代码textContent
<ax25:ar_final_rate>
<?php
ini_set('display_errors', 1);
$string='<soapenv:envelope xmlns:soapenv="http://www.w3.org/2003/05/soap-envelope">
<soapenv:body>
<ns:getrateresponse xmlns:ns="http://services.gts">
<ns:return xmlns:ax25="http://services.gts/xsd" xmlns:ax26="http://model.gts/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ax25:RaterResponseAutoQuotes">
<ax25:carriers xsi:type="ax25:RaterResponseCarriersAutoQuotes">
<ax25:accessorials xsi:type="ax25:RaterResponseAccessorial">
<ax25:aramount>12.66</ax25:aramount>
<ax25:accessorialid>22</ax25:accessorialid>
<ax25:accessorialname>Fuel</ax25:accessorialname>
</ax25:accessorials>
<ax25:ar_final_rate>161.66</ax25:ar_final_rate>
<ax25:carrier_id>0000087</ax25:carrier_id>
<ax25:carrier_name>CON-WAY FREIGHT INC</ax25:carrier_name>
<ax25:service_days>04</ax25:service_days>
</ax25:carriers>
<ax25:message>Success</ax25:message>
<ax25:referencenumber>3184877</ax25:referencenumber>
<ax25:success>true</ax25:success>
</ns:return>
</ns:getrateresponse>
</soapenv:body>
</soapenv:envelope>';
$domDocument = new DOMDocument();
$domDocument->loadXML($string);
$carriers=array();
$results=$domDocument->getElementsByTagNameNS("http://services.gts/xsd", "ar_final_rate");
foreach($results as $result)
{
array_push($carriers, $result->textContent);
}
print_r($carriers);
<强>输出:强>
Array
(
[0] => 161.66
)