有时候会遇到xml转换成数组的时候,xml里面的数据有可能是返回字符串,或者空,返回字符串时一切正常,但是但没有数据时,节点元素为空的情况下转换成数组就会出问题,那个空元素就会被转换成数组。
因为空节点在simplexml_load_string
函数转换后会是一个SimpleXMLElement
空对象,当你用json_encode
后也是空对象{}
,转成数组后自然是空数组。
解决方法看下面代码部分
$string = <<<XML
<?xml version='1.0'?>
<document>
<title>Forty What?</title>
<body></body>
<test name="fdsaf" ></test>
<testt id="aaa"><test id="a"><b></b></test></testt>
</document>
XML;
// 使用示例
print_r(parserXMLToArray($string,'array'));
/*
结果打印:
Array ( [title] => Forty What? [body] => [test] => [testt] => Array ( [test] => Array ( [b] => ) ) )
*/
/**
* parserXMLToArray
* XML Conversion to Arrays
* @param string $resp
* @param bool $format 默认object返回对象,需要返回数组请传入array
* @return bool|mixed|\SimpleXMLElement
* @author liuml <[email protected]>
* @DateTime 2018/12/19 9:58
*/
function parserXMLToArray($resp, $format = 'object')
{
$xml_parser = xml_parser_create();
if (!xml_parse($xml_parser, $resp, true)) {
xml_parser_free($xml_parser);
return false;
}
$disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
$respObject = simplexml_load_string($resp, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS | LIBXML_NOERROR);
libxml_disable_entity_loader($disableLibxmlEntityLoader);
if (false === $respObject) {
return false;
}
if ($format === 'array') {
return xmlObjectToArray($respObject);
}
return $respObject;
}
/**
* xmlObjectToArray xml对象转array,解决xml空元素的情况下转成空数组的问题
* @param $object
* @return mixed
* @author liuml <[email protected]>
* @DateTime 2019/1/24 17:31
*/
function xmlObjectToArray($object)
{
$result = [];
if (is_object($object)) {
$object = get_object_vars($object);
}
if (is_array($object)) {
foreach ($object as $key => $vo) {
if (is_object($vo)) {
$vo = xmlObjectToArray($vo);
}
if ($key != '@attributes') {
$result[$key] = $vo ? : '';
}
// 需要属性的话可以把下面注释去掉,上面一个判断注释掉
// if($key == '@attributes'){
// $result = $vo;
// }else{
// $result[$key] = $vo;
// }
}
}
return $result;
}