A su vez un elementos de la matriz vacíos [situación] PHP XML contiene elementos vacíos se convierte en una serie de cuestiones en relación con

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_stringla conversión función será un SimpleXMLElementobjeto nulo, cuando se utiliza json_encodeel 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;
}
Publicado 41 artículos originales · ganado elogios 21 · Vistas a 70000 +

Supongo que te gusta

Origin blog.csdn.net/u010324331/article/details/86630954
Recomendado
Clasificación