温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

php怎么将xml转为array数组

发布时间:2021-02-24 11:37:39 来源:亿速云 阅读:465 作者:小新 栏目:编程语言

这篇文章主要介绍php怎么将xml转为array数组,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

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

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数组”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI