【发布时间】:2011-09-04 06:25:31
【问题描述】:
我遇到了将 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 接口,但它仍然不能很好地用作具有多维数组的数组,即循环。
感谢大家的帮助
【问题讨论】:
-
这是什么原因?是循环的吗?因为在这种情况下,您应该能够毫无问题地循环 SimpleXMLElement 对象的各个部分。例如,如果您使用 SimpleXML 解析 ATOM 提要,您可以执行以下操作:
foreach($xml->entry as $entry),然后访问$entry->title等。从循环内。 -
请注意,将
(array)添加到上面(即@json_decode(@json_encode((array)$simple_xml_object ), 1);),如PHP 手册后面的注释中所述,可能会导致Node no longer exists错误。 -
这个问题是关于什么的? json_encode 对 simplexml 元素进行树遍历。你有什么不同的期望?你如何定义“有点hacky”?在您看来,这种方法有什么不可靠的地方?什么不高效?
-
这个问题我很清楚,所以我建议重新打开它。