业务中遇到要解析xml的情况:
先来看下xml数据的结构:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{
"code": "200",
"message": "",
"allCount": "3",
"data": [
{
"name": "zhangsan",
"sex": 0
},
{
"name": "lisi",
"sex": 1
},
{
"name": "wangwu",
"sex": 0
},
]
}</string>
最初用的以下这种方法实现了:
$res = file_get_contents("test.xml");
print_r(xmlToArray($res));
function xmlToArray($res){
$r = simplexml_load_string($res);
return json_decode($r[0],true);
}
但后来发现,如果数据量很大时,你想象我data中有50000多条数据,整个文件在30MB左右时出现个错误:
simplexml_load_string(): Entity: line 307585: parser error : xmlSAX2Characters: huge text node
经过多方找资料,后解决办法如下(参考资料:https://www.cnblogs.com/caicaizi/p/7837286.html):
$res = file_get_contents("test.xml");
print_r(xmlToArray2($res));
public static function xmlToArray2($res){
$p = xml_parser_create();
xml_parser_set_option($p, XML_OPTION_CASE_FOLDING, 1);
xml_parser_set_option($p, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($p, $res, $vals, $index);
xml_parser_free($p);
$jsonString = $vals[$index['STRING'][0]]['value'];
return json_decode($jsonString,true);
}