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删除特定数组内容并且重建数组索引的方法.

复制代码 代码如下: $a = array('a','b','c','d'); unset($a[2]); print_r($a); 但是这种方法的最大缺点是没有重建数组索引. 经过查资...

PHP实现动态执行代码的方法

本文实例讲述了PHP实现动态执行代码的方法。分享给大家供大家参考,具体如下: 这里介绍的PHP动态执行,即在页面上直接输入代码,点击执行,返回执行结果 方法很简单,主要使用了: $n...

php使用curl简单抓取远程url的方法

本文实例讲述了php使用curl抓取远程url的方法。分享给大家供大家参考。具体如下: cURL是一个非常有用的php库,可以用来连接不通类型的服务器和协议,下面是一个最基本的范例用来抓...

php面向对象之反射功能与用法分析

本文实例讲述了php面向对象之反射功能与用法。分享给大家供大家参考,具体如下: 个人对反射定义的理解: 首先得说说什么叫反射。对于一个新手来说,反射这个概念常常给人一种似懂非懂的 感觉,...

PHP中防止直接访问或查看或下载config.php文件的方法

或是,PHP的设计本身就避免直接查看文件内容的情况? 从安全角度考虑,这个系统级的文件应该做什么保护措施? 网友完善的答案 经调研,得出以下常用方法: 1 在程序中定义一个标识变量 复制...