php如何将获取到的xml解析为数组,这里我们可以使用系统函数,一步步解析即可。比如我们获取到xml数据源:
<MerChantResponse>
<code>00000000</code>
<msg>请求成功</msg>
<data>
<deviceId>869071037768299</deviceId>
<account>hy18360914</account>
<roleId>978300898</roleId>
<appId>0b1d013c50b94ffc987cb769037b91f2</appId>
<roleName>段满天</roleName>
<roleLevel>13</roleLevel>
<serverName>9783</serverName>
<total/>
</data>
</MerChantResponse>
首先将xml通过系统函数simplexml_load_string()将其转化成对象
object(SimpleXMLElement)#29 (3) {
["code"]=>
string(8) "00000000"
["msg"]=>
string(12) "请求成功"
["data"]=>
object(SimpleXMLElement)#30 (8) {
["deviceId"]=>
string(15) "869071037768299"
["account"]=>
string(10) "hy18360914"
["roleId"]=>
string(9) "978300898"
["appId"]=>
string(32) "0b1d013c50b94ffc987cb769037b91f2"
["roleName"]=>
string(9) "段满天"
["roleLevel"]=>
string(2) "13"
["serverName"]=>
string(4) "9783"
["total"]=>
object(SimpleXMLElement)#31 (0) {
}
}
}
接着使用json_encode()函数将对象转成json数据:
{"code":"00000000","msg":"\u8bf7\u6c42\u6210\u529f","data":{"deviceId":"869071037768299","account":"hy18360914","roleId":"978300898","appId":"0b1d013c50b94ffc987cb769037b91f2","roleName":"\u6bb5\u6ee1\u5929","roleLevel":"13","serverName":"9783","total":{}}}
最后使用json_decode()函数就获得数据的数组格式了:
array(3) {
["code"]=>
string(8) "00000000"
["msg"]=>
string(12) "请求成功"
["data"]=>
array(8) {
["deviceId"]=>
string(15) "869071037768299"
["account"]=>
string(10) "hy18360914"
["roleId"]=>
string(9) "978300898"
["appId"]=>
string(32) "0b1d013c50b94ffc987cb769037b91f2"
["roleName"]=>
string(9) "段满天"
["roleLevel"]=>
string(2) "13"
["serverName"]=>
string(4) "9783"
["total"]=>
array(0) {
}
}
}