Home > Article > Backend Development > How to convert xml into array in php
php method to convert xml into an array: first convert the xml data into object (object) format data; then use the json_encode() function to convert the object format into json format data; finally use the json_decode() function Just convert json format into array form.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Transfer xml data in php into array form, divided into three steps
1: Convert xml data into object format (simplexml_load_string() or simplexml_load_file())
2: Convert object (Object) into json format (json_encode())
3: Convert json format into array form (json_decode())
The difference between simplexml_load_string() and simplexml_load_file() methods:
simplexml_load_string() parameter is xml string
simplexml_load_file() parameter is xml file address or url
It can be achieved according to the above steps:
(1) Use simplexml_load_string method
$xml = '<?xml version="1.0" encoding="utf-8"?> <res> <test>test</test> <test1>test1</test1> <test2>test2</test2> </res>'; $xml =simplexml_load_string($xml); //xml转object $xml= json_encode($xml); //objecct转json $xml=json_decode($xml,true); //json转array echo '<pre class="brush:php;toolbar:false">'; print_r($xml);
(2) Use simplexml_load_file method
$xml =simplexml_load_file('./KPP-190107-0005.xml'); //xml转object $xml= json_encode($xml); //objecct转json $xml=json_decode($xml,true); //json转array echo '<pre class="brush:php;toolbar:false">'; print_r($xml);
Recommended learning: "PHP Video Tutorial》
The above is the detailed content of How to convert xml into array in php. For more information, please follow other related articles on the PHP Chinese website!