PHP如何将XML转成数组

yipeiwu_com5年前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获取表单中多个同名input元素的值

有时前台页面要允许动态增加/删除某项属性的多个值,比如向书架中添加书本,要可以动态增加或者删除书本。 前台页面的表单中会有多个input元素,如下: 复制代码 代码如下: <for...

php格式输出文件var_export函数实例

本文实例讲述了php格式输出文件var_export函数的用法。分享给大家供大家参考。具体如下: var_export:php 4 >= 4.2.0, php 5 var_expo...

php设计模式之适配器模式原理、用法及注意事项详解

本文实例讲述了php设计模式之适配器模式原理、用法及注意事项。分享给大家供大家参考,具体如下: 在这个有没有对象都要高呼“面向对象”的年代,掌握面向对象会给我们带来意想不到的方便。学编程...

浅谈使用PHP开发微信支付的流程

下面以PHP语言为例,对微信支付的开发流程进行一下说明。 1.获取订单信息 2.根据订单信息和支付相关的账号生成sign,并且生成支付参数 3.将支付参数信息POST到微信服务器,获取返...

PHP使用array_fill定义多维数组的方法

本文实例讲述了PHP使用array_fill定义多维数组的方法。分享给大家供大家参考。具体分析如下: PHP中可以用多个array_fill嵌套完成多维数组的定义: $creatio...