[英]I am not getting attribute name from xml response in php?
我從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
)
)
)
)
)
如果您閱讀有關SimpleXML的文章,那么您會發現執行print_r
並不能提供所有數據。 如果您想要field
元素的name
屬性,則可以執行以下操作:
$xml = new SimpleXMLElement($response);
foreach ( $xml->object[0]->field as $field ) {
echo $field['name'].PHP_EOL;
}
foreach
將獲取已加載的XML,然后選擇第一個object
元素([0]將選擇第一個object
元素),並在其中每個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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.