将 SimpleXML 对象转换为数组

我偶然发现了一个将 SimpleXML 对象转换为数组 这里的函数:

/**
* 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;
}

它工作得非常好,但是看起来有点古怪,是否有更有效/更健壮的方法来做到这一点?

我知道 SimpleXML 对象非常接近数组,因为它利用了 PHP 中的 ArrayAccess 接口,但是作为一个包含多维数组(即循环)的数组使用仍然不太好。

谢谢你的帮助

195902 次浏览

我在 PHP 手动注释里找到了这个:

/**
* 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。

在 simplexml 对象之前的代码中只缺少 (array):

...


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


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