Home > Backend Development > PHP Problem > How to convert xml into array in php

How to convert xml into array in php

青灯夜游
Release: 2023-03-08 15:34:01
Original
5073 people have browsed it

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.

How to convert xml into array in php

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 = &#39;<?xml version="1.0" encoding="utf-8"?>
        <res>
            <test>test</test>
            <test1>test1</test1>
            <test2>test2</test2>
        </res>&#39;;
$xml =simplexml_load_string($xml); //xml转object
$xml= json_encode($xml);  //objecct转json
$xml=json_decode($xml,true); //json转array
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($xml);
Copy after login

(2) Use simplexml_load_file method

$xml =simplexml_load_file(&#39;./KPP-190107-0005.xml&#39;); //xml转object
$xml= json_encode($xml);  //objecct转json
$xml=json_decode($xml,true); //json转array
echo &#39;<pre class="brush:php;toolbar:false">&#39;;
print_r($xml);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template