我从API获得XML响应,但我遇到了一个小问题。我无法从XML响应中获取name
属性。
这是我的代码,我试图获得name
属性,但我不能这样做请帮帮我。
$xml = new SimpleXMLElement($response);
echo "<pre>"; print_r($xml);die();
当我执行上面的代码时,它不显示name
属性,如order_id, origin,destination
。它显示0,1,2键而不是显示name
属性。
SimpleXMLElement Object
(
[@attributes] => Array
(
[version] => 1.0
)
[object] => SimpleXMLElement Object
(
[@attributes] => Array
(
[pk] => 1
[model] => awb
)
[field] => Array
(
[0] => 899594723
[1] => 800000041
[2] => 1.13
[3] => JHANSI - JHA
[4] => DELHI - DLO
[5] => DELHI - DLO
[6] => DLO
[7] => KAMASHYA ONLINE SHOPPING - 331428
[8] => R G
[9] => 28-Jan-2018
[10] => Delivered / Closed
[11] => Delivered
[12] => 999 - Delivered
[13] => Delivered
[14] => 999
[15] => Self:R G: Android
[16] => 0.0000000
[17] => 0.0000000
[18] => 01-Feb-2018
[19] => 01-Feb-2018
[20] => 01-Feb-2018 12:44
[21] => 2018-02-01 12:43:00
[22] => None
[23] => 0
[24] => 2018-02-01 12:44:20
[25] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rts_system_delivery_status
)
)
[26] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rts_reason_code_number
)
)
[27] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rts_last_update
)
)
[28] => 110019
[29] => DELHI
[30] => New Delhi
[31] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => delivery_pod_image
)
)
[32] => http://api3.ecomexpress.in//static/lastmile//sign/2018/2/1/sign_899594723_2018020112441517469260.png
[33] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rev_pickup_signature
)
)
[34] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rev_pickup_packed_image
)
)
[35] => SimpleXMLElement Object
(
[@attributes] => Array
(
[type] => CharField
[name] => rev_pickup_open_image
)
)
)
)
)
答案 0 :(得分:1)
如果您阅读了SimpleXML,那么您会发现执行print_r
并不能提供所有数据。如果您想要name
元素的field
属性,那么您可以执行以下操作...
$xml = new SimpleXMLElement($response);
foreach ( $xml->object[0]->field as $field ) {
echo $field['name'].PHP_EOL;
}
foreach
将获取加载的XML,然后选择第一个object
元素([0]将选择第一个元素)并且在每个field
元素中。 echo
行使用数组表示法来获取name
属性。
如果你想要一个特定的object
元素,那么你可以使用XPath来找到这个对象并执行与上面相似的操作并打印出来的每个元素......
$objectRec = $xml->xpath('//object[@pk="2"]')[0];
foreach ( $objectRec->field as $field ) {
echo $field['name'].PHP_EOL;
}
上面的XPath,挑出<object pk="2"...>
元素。请注意->xpath()
返回一个匹配节点数组,所以我再次使用第一个节点([0])。
为帮助检查您选择的元素以及print_r
何时没有多大帮助,您可以使用asXML()
输出节点的XML ...
$objectRec = $xml->xpath('//object[@pk="1"]')[0];
echo $objectRec->asXML();