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 模拟 asp.net webFrom 按钮提交事件的思路及代码

由于公司需要php方面的项目开发,php刚刚入门,在写按钮提交过程中,asp.net里的按钮事件更好些。先看下面的代码, 复制代码 代码如下:<?require_once '../...

PHP隐形一句话后门,和ThinkPHP框架加密码程序(base64_decode)

今天一个客户的服务器频繁被写入: mm.php 内容为: 复制代码 代码如下: <?eval($_POST[c]);?> 最后查到某文件内的第一行为以下代码: 复制代码 代...

写php分页时出现的Fatal error的解决方法

Fatal error: Cannot redeclare htmtocode() (previously declared in D:\www_local\mytest\conn.ph...

PHP排序算法之希尔排序(Shell Sort)实例分析

PHP排序算法之希尔排序(Shell Sort)实例分析

本文实例讲述了PHP排序算法之希尔排序(Shell Sort)。分享给大家供大家参考,具体如下: 基本思想: 希尔排序是指记录按下标的一定增量分组,对每一组使用 直接插入排序 ,随着增量...

php 邮件发送问题解决

这段时间修改了一下我们系统的登陆功能,为了更加安全,增加了发送邮件验证功能。当用户登陆的时候判断登陆ip是否是之前登陆过的,如果不是的话,需要向邮箱里发送验证码,然后把收到的验证码输入再...