Encontrado a veces cuando se convierten en un xml array, datos XML dentro puede ser una cadena, o nula, de retorno cadena todo a la normalidad, pero no hay datos pero, en el nodo en un elemento de matriz es la situación vacía será problemas, que los elementos vacíos se convertirán en una matriz.
Debido nodo vacío en simplexml_load_string
la conversión función será un SimpleXMLElement
objeto nulo, cuando se utiliza json_encode
el objeto vacío es {}
, naturalmente después de la transfección en una matriz vacía matriz.
Véase el siguiente porciones de código de Solución
$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;
}