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网络操作函数汇总

checkdnsrr — 给指定的主机(域名)或者IP地址做DNS通信检查 closelog — 关闭系统日志链接 define_syslog_variables — 初始化所有sysl...

PHP实现约瑟夫环问题的方法分析

本文实例讲述了PHP实现约瑟夫环问题的方法。分享给大家供大家参考,具体如下: 一、概述 先来看看网上比较常见的约瑟夫环问题描述:约瑟夫环(约瑟夫问题)是一个数学的应用问题:已知n个人(以...

php基于jquery的ajax技术传递json数据简单实例

本文实例讲述了php基于jquery的ajax技术传递json数据简单实现方法。分享给大家供大家参考,具体如下: html页面: <html> <head>...

php SQLite学习笔记与常见问题分析第1/2页

直到学会! 学之前找资料 SQLite的sql ATTACH DATABASE BEGIN TRANSACTION comment COMMIT ...

php 验证码(倾斜,正弦干扰线,黏贴,旋转)

php 验证码(倾斜,正弦干扰线,黏贴,旋转)

好久没有写帖子了。一直忙着新的项目。 最近,做验证码程序,一直想做一个简洁大方,自动识别比较困难的。 通过这些时候整理搜集,发现一般做法有以下几种方案:1、字体变型 (一般通过算法,进行...