本文介绍如何使用php函数解析xml数据为数组。
php
<?php
$a = '<xml><ToUserName><![CDATA[ww8b77afac71336111]]></ToUserName><FromUserName><![CDATA[sys]]></FromUserName><CreateTime>1736328669</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[change_external_contact]]></Event><ChangeType><![CDATA[del_external_contact]]></ChangeType><UserID><![CDATA[Xu]]></UserID><ExternalUserID><![CDATA[woh0dIDAAA4kq6S_aXw1UkX7_qXb22ng]]></ExternalUserID></xml>';
$xmlObject = simplexml_load_string($a,'SimpleXMLElement', LIBXML_NOBLANKS);
$json = json_encode($xmlObject);
var_dump($json);
$array = json_decode($json, true);
print_r($array);
打印后发现xml内容中带有CDATA的好像不能正常解析
string(133) "{"ToUserName":{},"FromUserName":{},"CreateTime":"1736328669","MsgType":{},"Event":{},"ChangeType":{},"UserID":{},"ExternalUserID":{}}"
Array
(
ToUserName\] =\> Array ( ) \[FromUserName\] =\> Array ( ) \[CreateTime\] =\> 1736328669 \[MsgType\] =\> Array ( ) \[Event\] =\> Array ( ) \[ChangeType\] =\> Array ( ) \[UserID\] =\> Array ( ) \[ExternalUserID\] =\> Array ( ) )


看起来不错,我来替换下尝试一下
string(239) "{"ToUserName":"ww8b77afac713361bd","FromUserName":"sys","CreateTime":"1736328669","MsgType":"event","Event":"change_external_contact","ChangeType":"del_external_contact","UserID":"XuBin","ExternalUserID":"woh0dIDAAA4kq6S_aXw1UkX7_qXb22ng"}"
Array
(
ToUserName\] =\> ww8b77afac71336111 \[FromUserName\] =\> sys \[CreateTime\] =\> 1736328669 \[MsgType\] =\> event \[Event\] =\> change_external_contact \[ChangeType\] =\> del_external_contact \[UserID\] =\> Xu \[ExternalUserID\] =\> woh0dIDAAA4kq6S_aXw1UkX7_qXb22ng )