Home  >  Article  >  Backend Development  >  How to convert xml to array in php

How to convert xml to array in php

青灯夜游
青灯夜游Original
2021-02-24 11:00:223376browse

Method: First use simplexml_load_string() to convert the XML string into a SimpleXMLElement object; then use json_encode() to convert the object into JSON data; finally use json_decode() to convert the JSON data into an array.

How to convert xml to array in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

php converts xml For the array number

1. Function:

/*
@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() function converts a well-formed XML string into a SimpleXMLElement object.

json_encode() is used to JSON encode variables. This function returns JSON data if executed successfully, otherwise it returns FALSE.

json_decode() function is used to decode a JSON-formatted string and convert it into a PHP variable (object or array).

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

Parameters

  • ##json_string: JSON string to be decoded, must be UTF-8 encoded data

  • assoc: When this parameter is TRUE, an array is returned, and when FALSE, an object is returned.

  • depth: Integer type parameter, which specifies the recursion depth

  • options: Binary mask, currently only JSON_BIGINT_AS_STRING is supported.

2. Test:

a. Code:

<?php
$string = <<<XML
<?xml version=&#39;1.0&#39;?> 
<document>
<title>Forty What?</title>
<from>Joe</from>
<to>Jane</to>
<body>
I know that&#39;s the answer -- but what&#39;s the question?
</body>
</document>
XML;
$arr = xmltoarray($string);
var_dump($arr);

b. Output:

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

For more programming-related knowledge, please visit:

Programming Video! !

The above is the detailed content of How to convert xml to array in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn