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操作XML作为数据库的类

xml.class.php文件代码复制代码 代码如下: <?php * example 读取数据: * * $xml = new xml("dbase.xml",'table');...

php+xml结合Ajax实现点赞功能完整实例

本文实例讲述了php+xml结合Ajax实现点赞功能的方法。分享给大家供大家参考。具体如下: 使用xml、php和Ajax实现点赞功能,不需要链接数据库,使用php来修改xml的内容,使...

php 函数使用可变数量的参数方法

php在用户自定义函数中支持可变数量的参数列表。 在php5.5及更早的版本中,使用func_num_args(), func_get_arg(), func_get_args()函数实...

PHP生成唯一的促销/优惠/折扣码(附源码)

每一个电子商务网站,现在有一种或多种类型的优惠/折扣/优惠券系统,给大家分享一下如何在PHP生成唯一的促销/折扣码。主要是实现一个优惠码系统,可用于跟踪用户来自某些特定的来源,例如有些主...

php正则preg_replace_callback函数用法实例

本文实例讲述了php正则preg_replace_callback函数的用法。分享给大家供大家参考。具体实现方法如下: php正则表达式功能强大,本范例演示了preg_replace_c...