将SimpleXML对象转换为数组

时间:2011-05-29 10:48:07

标签: php xml arrays

我遇到了将SimpleXML对象转换为数组here

的功能
/**
 * function object2array - A simpler way to transform the result into an array 
 *   (requires json module).
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  Diego Araos, diego at klapmedia dot com
 * @date    2011-02-05 04:57 UTC
 * @link    http://www.php.net/manual/en/function.simplexml-load-string.php#102277
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function object2array($object)
{
    return json_decode(json_encode($object), TRUE); 
}

所以我对XML字符串的采用就像:

function xmlstring2array($string)
{
    $xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

    $array = json_decode(json_encode($xml), TRUE);

    return $array;
}

它运作得很好,但看起来有点hacky?有没有更有效/更强大的方法来做到这一点?

我知道SimpleXML对象足够接近数组,因为它在PHP中使用了ArrayAccess接口,但它仍然不能很好地用作具有多维数组的数组,即循环。

感谢大家的帮助

2 个答案:

答案 0 :(得分:81)

我在PHP manual comments

中找到了这个
/**
 * function xml2array
 *
 * This function is part of the PHP manual.
 *
 * The PHP manual text and comments are covered by the Creative Commons 
 * Attribution 3.0 License, copyright (c) the PHP Documentation Group
 *
 * @author  k dot antczak at livedata dot pl
 * @date    2011-04-22 06:08 UTC
 * @link    http://www.php.net/manual/en/ref.simplexml.php#103617
 * @license http://www.php.net/license/index.php#doc-lic
 * @license http://creativecommons.org/licenses/by/3.0/
 * @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
 */
function xml2array ( $xmlObject, $out = array () )
{
    foreach ( (array) $xmlObject as $index => $node )
        $out[$index] = ( is_object ( $node ) ) ? xml2array ( $node ) : $node;

    return $out;
}

它可以帮到你。但是,如果将XML转换为数组,则会丢失可能存在的所有属性,因此您无法返回XML并获取相同的XML。

答案 1 :(得分:49)

在simplexml对象之前,代码中缺少(array)

...

$xml   = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);

$array = json_decode(json_encode((array)$xml), TRUE);
                                 ^^^^^^^
...