php如何将xml转为array数组

青灯夜游
青灯夜游原创
2023-03-08 09:04:012400浏览

方法:首先用simplexml_load_string()将XML字符串转换为SimpleXMLElement对象;然后用json_encode()将该对象转换为JSON数据;最后用json_decode()将JSON数据转换为数组即可。

本教程操作环境:windows7系统、PHP7.1版,DELL G3电脑

php将xml转换为array数

1、函数:

/*
@desc:xml转数组
@param data xml字符串
@return arr 解析出的数组
*/
function xmltoarray($data){
$obj = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
$json = json_encode($obj);
$arr = json_decode($json, true);      
return $arr;
}

simplexml_load_string() 函数转换形式良好的 XML 字符串为 SimpleXMLElement 对象。

json_encode() 用于对变量进行 JSON 编码,该函数如果执行成功返回 JSON 数据,否则返回 FALSE 。

json_decode() 函数用于对 JSON 格式的字符串进行解码,并转换为 PHP 变量(对象或数组)。

json_decode ($json_string [,$assoc = false [, $depth = 512 [, $options = 0 ]]])

参数

  • json_string: 待解码的 JSON 字符串,必须是 UTF-8 编码数据

  • assoc: 当该参数为 TRUE 时,将返回数组,FALSE 时返回对象。

  • depth: 整数类型的参数,它指定递归深度

  • options: 二进制掩码,目前只支持 JSON_BIGINT_AS_STRING 。

2、测试:

a. 代码:

<?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;
$arr = xmltoarray($string);
var_dump($arr);

b. 输出:

array(4) {
["title"]=>
string(11) "Forty What?"
["from"]=>
string(3) "Joe"
["to"]=>
string(4) "Jane"
["body"]=>
string(57) "
I know that's the answer -- but what's the question?
"
}

更多编程相关知识,请访问:编程视频!!

以上就是php如何将xml转为array数组的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。