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)

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

相关文章

关于Zend Studio 配色方案插件的介绍

关于Zend Studio 配色方案插件的介绍

首先,菜单栏–help–install new software… 接着,添加一个更新源,就是点击界面的add按钮,在新窗口的location位置输入http://eclipse-col...

利用Laravel事件系统如何实现登录日志的记录详解

本文介绍的是利用Laravel事件系统实现登录日志记录的相关内容,分享出来给大家参考,下面来看看详细的介绍: 明确需求 记录一个登录日志,通常需要下列信息: 客户端Agent信息...

全面解读PHP的Yii框架中的日志功能

Yii页面级日志开启 在 Main.php中 log段添加、 下面显示页面日志 array( 'class'=>'CWebLogRoute', 'levels'=>'tra...

在普通HTTP上安全地传输密码

1。理论      在普通HTTP上,一般表单中的密码都是以明文方式传到服务器进行处理的。这无疑给了坏人以可乘之机!这里我们就说说怎么传...

php数组函数序列之in_array() 查找数组值是否存在

in_array() 定义和用法 in_array() 函数在数组中搜索给定的值。 语法 in_array(value,array,type) 参数 描述 value 必需。规定要在数组...