PHP如何将XML转成数组

yipeiwu_com6年前PHP代码库

如果你使用 curl 获取的 xml data
xml=simplexmlloadstring(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);
如果是直接获取 URL 数据的话
xml=simplexmlloadfile(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);

先把 simplexml 对象转换成 json,再将 json 转换成数组。

代码:

<?php
$string = <<<XML
<?xml version='1.0'?> 
<document>
 <title>Forty What?</title>
 <from>Joe</from>
 <to>Jane</to>
 <body>
 I know that's the answer -- but what's the question?
 </body>
</document>
XML;

$xml=simplexml_load_string($string);
$data = json_decode(json_encode($xml),TRUE);
var_dump( $xml );
var_dump( $data );
object(SimpleXMLElement)[1]
 public 'title' => string 'Forty What?' (length=11)
 public 'from' => string 'Joe' (length=3)
 public 'to' => string 'Jane' (length=4)
 public 'body' => string '
 I know that's the answer -- but what's the question?
 ' (length=57)
array
 'title' => string 'Forty What?' (length=11)
 'from' => string 'Joe' (length=3)
 'to' => string 'Jane' (length=4)
 'body' => string '
 I know that's the answer -- but what's the question?
 ' (length=57)

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关文章

PHP计算近1年的所有月份

PHP计算近1年的所有月份

话不多说,请看代码:  $z = date('Y-m'); $a = date('Y-m', strtotime('-12 months')); $begin = new...

Yii2中简单的场景使用介绍

本文主要介绍的是关于Yii2简单场景使用的相关内容,分享出来供大家参考学习,下面来一起看看详细的介绍: 直接上代码(主要部分): 模型层: public function rule...

ThinkPHP使用心得分享-分页类Page的用法

ThinkPHP中的Page类在ThinkPHP/Extend/Library/ORG/Util/Page.class.php中,所以使用前要引入Page类: 复制代码 代码如下:imp...

关于url地址传参数时字符串有回车造成页面脚本赋值失败的解决方法

在通过url地址接受参数的时候,有些参数的值V带有回车' %0A ',这时候在页面脚本显示的时候,把这个值V付给脚本变量,可能会造成脚本的错误。 所以,相应的:一开始在传值的时候对一些字...

php实现以只读方式打开文件的方法

本文实例讲述了php实现以只读方式打开文件的方法。分享给大家供大家参考。具体分析如下: php中可以通过fopen()打开一个文件,第二个参数设置为"r"表示已只读方式打开,函数返回一个...