Sometimes encountered when converted into an array xml, xml data inside there may be a String, or null, string return everything to normal, but there is no data but, at the node into an array element is empty situation it will be problems, that empty elements will be converted into an array.
Because empty node in simplexml_load_string
the function conversion will be a SimpleXMLElement
null object, when you use json_encode
the empty object is {}
, naturally after transfection into an array empty array.
See the following code portions Solution
$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;
}