mysql xml字符串转数组_php如何将xml转为array数组

方法:首先用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 = <<Forty What?

Joe

Jane

I know thats the answer -- but whats the question?

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 thats the answer -- but whats the question?

"

}

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

方法:首先用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. 代码: string(11) "Forty What?" ["from"]=> string(3) "Joe" ["to"]=> string(4) "Jane" ["body"]=> string(57) " I know thats the answer -- but whats the question? " } 更多编程相关知识,请访问:编程视频!!
经验分享 程序员 微信小程序 职场和发展