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下使用SimpleXML 处理XML 文件

1 SimpleXML 简介 要处理XML 文件,有两种传统的处理思路:SAX 和DOM。SAX 基于事件触发机制, 对XML 文件进行一次扫描,完成要进行的处理;DOM 则将整个XML...

PHP随机生成唯一HASH值自定义函数

网上有很多种方法获取随机唯一的HASH值,但是大同小异: 1、先获取随机的唯一字符串 2、进行MD5或者sha1算HASH值 一个项目要用到hash值,就去网上找了找,却发现PHP有一个...

php 引用(&amp;)详解

在PHP 中引用的意思是:不同的名字访问同一个变量内容. 与C语言中的指针是有差别的.C语言中的指针里面存储的是变量的内容在内存中存放的地址 变量的引用 PHP 的引用允许你用两个变量来...

php unset全局变量运用问题的深入解析

PHP unset全局变量在实际使用中只能销毁局部变量,并不能实现全局变量的目的。下面我们就来具体解决这一问题。希望对大家有所帮助。PHP中语言中有些函数对于初学者来说在字面上是很难理解...

在任意字符集下正常显示网页的方法二(续)

转:coolcode.cn 前几天写了一篇在任意字符集下正常显示网页的方法,里面介绍的很简单,就是把前128个字符以外的字符集都用 NCR 来表示,但是具体怎么转化我...