gpt4 book ai didi

php - 将 SimpleXML 对象转换为数组

转载 作者:IT老高 更新时间:2023-10-28 12:01:52 24 4
gpt4 key购买 nike

我遇到了将 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 接口(interface),但它仍然不能很好地用作具有多维数组的数组,即循环。

感谢大家的帮助

最佳答案

我在 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。

关于php - 将 SimpleXML 对象转换为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6167279/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com