我正在从api请求接收xml数据,但我发现它很难解析。我已经提供了一个示例,其中包含响应数据的外观以及如何解析它的示例。我已经包含了用于解析XML的代码。我的问题是使用$xml->xpath('//SOAP-ENV:Body/ns1:add_purchase_orderResponse/return/item/value/item/value')
不是很用户友好,我更喜欢使用$xml->xpath('//SOAP-ENV:Body/ns1:add_purchase_orderResponse/return/result/status/code')
我做错了什么,或者我只是因为我获取的是丑陋的XML而停留在丑陋的代码上。
<?php
$orderXML = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:ns1="http://qqp.mypresswise.com/r/wsdl-order.php"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:ns2="http://xml.apache.org/xml-soap"
xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:add_purchase_orderResponse>
<return xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">result</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">status</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">code</key>
<value xsi:type="xsd:int">0</value>
</item>
<item>
<key xsi:type="xsd:string">text</key>
<value xsi:type="xsd:string">ok</value>
</item>
</value>
</item>
<item>
<key xsi:type="xsd:string">data</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">webID</key>
<value xsi:type="xsd:string">ZTJmYTA0NmI4NmVk</value>
</item>
<item>
<key xsi:type="xsd:string">orderID</key>
<value xsi:type="xsd:string">44604</value>
</item>
<item>
<key xsi:type="xsd:string">items</key>
<value xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">item</key>
<value SOAP-ENC:arrayType="ns2:Map[1]" xsi:type="SOAP-ENC:Array">
<item xsi:type="ns2:Map">
<item>
<key xsi:type="xsd:string">itemID</key>
<value xsi:type="xsd:int">107263</value>
</item>
<item>
<key xsi:type="xsd:string">itemprice</key>
<value xsi:type="xsd:string">42</value>
</item>
</item>
</value>
</item>
</value>
</item>
</value>
</item>
</value>
</item>
</return>
</ns1:add_purchase_orderResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
XML;
$xml = simplexml_load_string($orderXML);
foreach($xml->xpath('//SOAP-ENV:Body/ns1:add_purchase_orderResponse/return/item/value/item/value') as $xmlItem) {
/*if ($xmlItem->item[0]->key == "code"){
echo "value=>" . $xmlItem->item[0]->value;
} */
if ($xmlItem->item[1]->key == "orderID"){
echo "value=>" . $xmlItem->item[1]->value;
}
}
?>