Home > Article > Backend Development > How to convert xml to array in php
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.
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
2. Test:
<?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. Output:
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? " }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!