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中file_get_contents与curl性能比较分析

php中file_get_contents与curl性能比较分析

本文实例讲述了php中file_get_contents与curl性能比较分析。分享给大家供大家参考。具体如下: 在php中如果不仔细的去分析性能会发现file_get_contents...

PHP函数常用用法小结

魔术函数   魔术函数是PHP中内置的语言特性,当程序执行到某种情况时,如果定义了这些魔术函数(php手册中称之为“Overloading”),则PHP会调用他们,同时也会传入...

PHP简单实现欧拉函数Euler功能示例

本文实例讲述了PHP简单实现欧拉函数Euler功能。分享给大家供大家参考,具体如下: 欧拉函数ph(n)的意思是所有小于n且与n互质的个数。 比如说ph(10) = 4{1,3,7,9与...

关于ob_get_contents(),ob_end_clean(),ob_start(),的具体用法详解

ob_get_contents();ob_end_clean();ob_start()使用ob_start()把输出那同输出到缓冲区,而不是到浏览器。然后用ob_get_contents...

PHP采用自定义函数实现遍历目录下所有文件的方法

目录的遍历是PHP程序设计中经常会用到的一个功能,很多PHP项目都有这一功能模块。今天本文就来实例解析一下PHP采用自定义函数实现遍历目录下所有文件的方法。具体方法如下: 方法一:使用r...