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自动生成印有用户信息的名片

利用PHP自动生成印有用户信息的名片

前言 无论是自己要在精心P过的自拍上添加个性文字,或者是摄影爱好者要在拍摄的作品里添加水印,亦或是在网页或者移动应用中实时生成文字和图片的组合,我们都需要找到一个合适且靠谱的方法来将图片...

解析php php_openssl.dll的作用

一.openssl简介数据加密是信息信息传输中的一个重要组成部分.任何信息都以明文方式传输,确实是个很不安全的做法.所以, 需要对数据进行加密.将明文数据转换为密文数据,再进行传输....

比file_get_contents稳定的curl_get_contents分享

分享一个实际在用的函数: 复制代码 代码如下: /*比file_get_contents稳定的多!$timeout为超时时间,单位是秒,默认为1s。*/ function curl_ge...

php中通过虚代理实现延迟加载的实现代码

这货是从 Martin 大神的《企业应用架构模式》中学到的,辅助 PHP 动态语言的特性,可以比 Java 轻松很多的实现延迟加载(LazyLoad)。基本原理是通过一个虚代理(Virt...

php简单判断两个字符串是否相等的方法

本文实例讲述了php简单判断两个字符串是否相等的方法。分享给大家供大家参考。具体实现方法如下: <?php function strcomp($str1,$str2)...