开发者社区> 问答> 正文

将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接口,但与多维数组(即循环)一起使用时,仍然不能很好地工作。

谢谢大家的帮助问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 22:06:45 641 0
1 条回答
写回答
取消 提交回答
  • 我在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。

    2020-02-08 22:07:00
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载