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)

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

相关文章

关于zend studio 出现乱码问题的总结

出现乱码的地方大概有4个地方:1、文件的编码方式(就是你新建文件的编码),这一点需要设置编辑器的编码方式。2、页面没有指定浏览器编码的显示方式,这一点解决的办法是:1,如果页面是.htm...

php使用scandir()函数扫描指定目录下所有文件示例

本文实例讲述了php使用scandir()函数扫描指定目录下所有文件。分享给大家供大家参考,具体如下: //遍历子文件夹和文件夹的内容 并且计算出文件的多少 //一个demo 引号替...

PHP读取CURL模拟登录时生成Cookie文件的方法

PHP读取CURL模拟登录时生成Cookie文件的方法

本文实例讲述了PHP读取CURL模拟登录时生成Cookie文件的方法。分享给大家供大家参考。具体实现方法如下: 在使用PHP中的CURL模拟登录时会保存一个Cookie文件,例如下面的代...

php 记录进行累加并显示总时长为秒的结果

现在有一个mysql数据库的test表里有一个duration字段,里面有三条记录: 00:22:32 13:42:21 134:42:21 表示的是时长,但是,保存类型是文本。 现在要...

php 结果集的分页实现代码

复制代码 代码如下:<?php @mysql_connect("localhost", "root","1981427") //连接数据库服务器 or die("数据库服务器连接失...