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)

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

相关文章

10个值得深思的PHP面试题

10个值得深思的PHP面试题

文章所罗列的问题虽然看似简单,但是每个背后都涵盖了一个或几个大家容易忽视的基础知识点,希望能够帮助到你的面试和平时工作。 Q1 第一个问题关于弱类型 $str1 = 'yabadab...

PHP面向对象分析设计的61条军规小结

(1)所有数据都应该隐藏在所在的类的内部。 (2)类的使用者必须依赖类的共有接口,但类不能依赖它的使用者。 (3)尽量减少类的协议中的消息。 (4)实现所有类都理解的最基本公有接口[例如...

PHP实现15位身份证号转18位的方法分析

本文实例讲述了PHP实现15位身份证号转18位的方法。分享给大家供大家参考,具体如下:第一代身份证:15位身份证号码的意义1-2位省、自治区、直辖市代码; 3-4位地级市、盟、自治州代码;...

php 生成随机验证码图片代码

复制代码 代码如下:<?php /** 默认首页 **/ class DefaultController extends AppController { public functi...

php编译安装php-amq扩展简明教程

本文讲述了php编译安装php-amq扩展的方法。分享给大家供大家参考,具体如下: 用途:这个扩展是用来操作rabbitmq服务端的 一、安装总括 1、编译安装librabbitmq库...