版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hai7425/article/details/83045059
<?
/*
通过SimpleXMLElement Object获取的数据不好操作,需要转化为普通数组。发现通过json_decode和json_encode可以转化。
参考教程http://www.runoob.com/php/func-simplexml-load-string.html
*/
$postStr = '<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1348831860</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[this is a test]]></Content>
<MsgId>1234567890123456</MsgId>
</xml>';
$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
$jsonStr = json_encode($postObj);
$jsonArray = json_decode($jsonStr,true);
echo "<pre>";
print_r($jsonArray);
echo "<pre>";
$arr= object_array($postObj);
echo "<pre>";
print_r($arr);
echo "<pre>";
function object_array($array){
if(is_object($array)){
$array = (array)$array;
}
if(is_array($array)){
foreach($array as $key=>$value){
$array[$key] = object_array($value);
}
}
return $array;
}
?>