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)

以上就是本文的全部内容,希望对大家的学习有所帮助。

相关文章

访问编码后的中文URL返回404错误的解决方法

访问编码后的中文URL返回404错误的解决方法

昨天做一个项目,其中有一个需求是每一张图片对应一小段文字对图片的说明,普通的做法是新建一个表然后把图片名与说明文字都记录到数据库内。仔细考虑后感觉这个应用不要数据库也能完成,我实现的方案...

php使用Jpgraph绘制简单X-Y坐标图的方法

php使用Jpgraph绘制简单X-Y坐标图的方法

本文实例讲述了php使用Jpgraph绘制简单X-Y坐标图的方法。分享给大家供大家参考。具体实现方法如下: <?php include ("src/jpgraph.p...

win10环境PHP 7 安装配置【教程】

PHP 7出来好一段时间了,前些日子工作比较忙,没时间研究,现在有点时间了,公司里生产环境不能随便升级,家里自己的电脑还是可以装一下看看效果的。 下面简单说明一下PHP 7 + Apac...

eAccelerator的安装与使用详解

一、PHPeAccelerator安装去https://github.com/eaccelerator/eaccelerator/downloads下载最新版安装包,解压安装包,进入解压...

UCenter Home二次开发指南

前言本文将就UCH二次开发这个核心主题,以各种实现的代码为主,辅助部分说明概略的讲解如何针对UCH进行二次开发。过段时间UCH就开源了,准备到时候再详细的写篇UCH机制分析。 顺便说下,...