PHP如何将XML转成数组

yipeiwu_com5年前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)

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

相关文章

phpmailer绑定邮箱的实现方法

phpmailer绑定邮箱的实现方法

本文实例讲述了phpmailer绑定邮箱的实现方法。分享给大家供大家参考,具体如下: 效果如下: 1.配置 <?php return array ( 'email...

php 如何获取数组第一个值

reset (PHP 3, PHP 4, PHP 5)reset -- 将数组的内部指针指向第一个单元 说明mixed reset ( array &array )reset() 将 a...

解析thinkphp基本配置 convention.php

复制代码 代码如下:return  array(     /* 项目设定 */    'APP_DEBUG'&nbs...

PHP中使用数组实现堆栈数据结构的代码

在堆栈中,最后压入的数据(进栈),将会被最先弹出(出栈)。 即在数据存储时采用“先进后出”的数据结构。 PHP中,将数组当做一个栈,主要是使用array_push()和array_pop...

PHP获取中英混合字符串长度的方法

今晚在写框架的表单验证类时,需要判断某个字符串长度是否在指定区间内,很自然地,想到了PHP中的strlen函数。复制代码 代码如下:$str = 'Hello world!';echo...