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使用PHPexcel导入导出数据的方法

本文实例讲述了PHP使用PHPexcel导入导出数据的方法。分享给大家供大家参考,具体如下: 导入数据: <?php error_reporting(E_ALL); /...

php从数据库查询结果生成树形列表的方法

本文实例讲述了php从数据库查询结果生成树形列表的方法。分享给大家供大家参考。具体分析如下: 本代码可以从数据库读取数据生成一个类似于windows的资源管理器的树形列表 <&...

php中json_encode中文编码问题分析

例如:'胥'经过json_encode处理后变为'\u80e5',最终的json中中文部分被替换为unicode编码。我们要解决的就是将对象转换为json并保证对象内部的中文在json中...

PHP封装类似thinkphp连贯操作数据库Db类与简单应用示例

本文实例讲述了PHP封装类似thinkphp连贯操作数据库Db类与简单应用。分享给大家供大家参考,具体如下: <?php header("Content-Type:te...

基于php常用函数总结(数组,字符串,时间,文件操作)

数组:【重点1】implode(分隔,arr) 把数组值数据按指定字符连接起来例如:$arr=array('1','2','3','4');$str=implode('-',$arr);...