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 bootstrap实现简单登录

php bootstrap实现简单登录

本文实例为大家分享了php bootstrap实现简单登录的方法,供大家参考,具体内容如下 所有文件 记住是获取name键值对 from 里面 action就是你的动作 si...

PHP中使用cURL实现Get和Post请求的方法

1.cURL介绍   cURL 是一个利用URL语法规定来传输文件和数据的工具,支持很多协议,如HTTP、FTP、TELNET等。最爽的是,PHP也支持 cURL 库。本文将介绍 cU...

php checkbox 取值详细说明

设我们有一个html页面,代码如下: 复制代码 代码如下: <FORM method="post" action="checkTest.php"> <INPUT nam...

php中bind_param()函数用法分析

php中bind_param()函数用法分析

本文实例讲述了php中bind_param()函数用法。分享给大家供大家参考,具体如下: 从字面上不难理解,绑定的参数;下面我通过一个绑定参数的例子讲一下: for example: b...

php数组冒泡排序算法实例

本文实例讲述了php数组冒泡排序算法。分享给大家供大家参考,具体如下: <?php /*@冒泡排序算法 */ $array=array(5,45,22,11,32,28...