PHP如何将XML转成数组

yipeiwu_com5年前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分页时出现的Fatal error的解决方法

Fatal error: Cannot redeclare htmtocode() (previously declared in D:\www_local\mytest\conn.ph...

PHP实现图片压缩的两则实例

本文介绍了PHP实现图片压缩的两种方法,读者可以根据具体应用参考或加以改进,以适应自身应用需求!废话不多说,主要代码部分如下: 实例1: <?php /** * d...

PHP设计模式之观察者模式定义与用法分析

本文实例讲述了PHP设计模式之观察者模式定义与用法。分享给大家供大家参考,具体如下: 观察者模式 当一个对象的状态发生改变时,依赖他的对象会全部收到通知,并自动更新 场景:当一个事件发生...

php删除数组中重复元素的方法

几种php删除数组元素方法在很多情况下我们的数组会出现重复情况,那我们删除数组中一些重复的内容怎么办,这些元素必须保持他唯一,所以就想办法来删除它们,下面利用了遍历查询来删除重复数组元素...

PHP has encountered an Access Violation 错误的解决方法

搭建wordpress的时候发觉居然会报这种错误,网上的解决方案都是千篇一律的复制粘贴,都是关于eaccelerator的设置问题,我很奇怪我并没有安装这个扩展啊?不过倒是安装过APC扩...