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 观察者模式深入理解与应用分析

PHP 观察者模式深入理解与应用分析

本文实例讲述了PHP 观察者模式。分享给大家供大家参考,具体如下: 用模式开发的优点是,能让我们的逻辑结构以及代码更加清晰,便于维护! 而我们为什么要用 “观察者模式”?这就需要从实际运...

PHP获取HTTP body内容的方法

有时候我们获取数据时需要根据Header中的格式来解析,比如上传一个json而不是一个文本。这里用到了 php输入|输出流 的概念。 PHP 提供了一些杂项输入/输出(IO)流,允许访问...

使用adodb lite解决问题

我使用adodb完整版的时候, 服务器竟然不支持,我差点自己去写个类, 把adodb的函数实现,以致我不用改我的程序但是现在我用了adodb-lite,这个是简化的版本,还不错,挺好的h...

php实现删除指定目录下相关文件的方法

本文实例讲述了php实现删除指定目录下相关文件的方法。分享给大家供大家参考。具体实现方法如下: 通常来说在php中删除文件最简单的方法就是直接使用unlink命令,而对于需要删除指定目录...

PHP代码优化之成员变量获取速度对比

有如下4个代码示例,你认为他们创建对象,并且获得成员变量的速度排序是怎样的? 1:将成员变量设置为public,通过赋值操作给成员变量赋值,直接获取变量复制代码 代码如下:<?ph...