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 单引号与双引号的区别

1、定义字符串   在PHP中,字符串的定义可以使用单引号,也可以使用双引号。但是必须使用同一种单或双引号来定义字符串,如:‘Hello"和“Hello'为非法的字符串定义。    定义...

PHP数组循环操作详细介绍 附实例代码

PHP数组还是比较常用的,于是我研究了一下PHP数组循环操作,在这里拿出来和大家分享一下,希望对大家有用。PHP基本上就是一种数组语言。时常要进行大量的PHP数组循环操作,主要有两种方式...

PHP查询大量数据内存耗尽问题的解决方法

从数据库查询大量数据时会出现内容不够的提示: PHP Fatal error: Allowed memory size of 268 435 456 bytes exhausted 这个...

php 智能404跳转代码,适合换域名没改变目录的网站

复制代码 代码如下: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.o...

php 无限极分类

复制代码 代码如下:<?php /*======================================================== 类名:catalog 功能:无...