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类与对象后期静态绑定操作实例详解

本文实例讲述了PHP类与对象后期静态绑定操作。分享给大家供大家参考,具体如下: 做项目是后期静态绑定非常有用。比如service层单例模式,使用后期静态绑定就非常好实现。 自 PHP 5...

一段php加密解密的代码

<?php   $key = "This is supposed to be a ...

php中get_magic_quotes_gpc()函数说明

get_magic_quotes_gpc函数是一个用来判断是否为用户提供的数据增加斜线了,这个在php.ini配置文件中哦,下面我来介绍一下get_magic_quotes_gpc()函...

PHP类的封装与继承详解

封装        把成员方法和成员属性封装到类中,隐藏属性和方法实现的细节,通过public、protected、priva...

PHP连接SQLServer2005的方法

PHP连接SQLServer2005的方法

1.修改php.ini将extension=php_mssql.dll的注释删除保存。 修改php.in将mssql.secure_connection = Off改为mssql.sec...