我碰到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接口,但是与多维数组(即循环)一起使用时,仍然不能很好地工作。
谢谢大家的帮助
foreach($xml->entry as $entry)
然后访问$entry->title
et.c。从循环内。