PHP method and example code for converting XML into array

墨辰丷
Release: 2023-03-29 16:58:01
Original
1341 people have browsed it

This article mainly introduces in detail the method of converting XML into an array in PHP. Interested friends can refer to it

If you use the xml data obtained by curl
xml=simplexmlloadstring(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);
If the URL data is obtained directly
xml=simplexmlloadfile(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);

Convert the simplexml object to json first, and then json Convert to array.

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;

$xml=simplexml_load_string($string);
$data = json_decode(json_encode($xml),TRUE);
var_dump( $xml );
var_dump( $data );
Copy after login

object(SimpleXMLElement)[1]
 public &#39;title&#39; => string &#39;Forty What?&#39; (length=11)
 public &#39;from&#39; => string &#39;Joe&#39; (length=3)
 public &#39;to&#39; => string &#39;Jane&#39; (length=4)
 public &#39;body&#39; => string &#39;
 I know that&#39;s the answer -- but what&#39;s the question?
 &#39; (length=57)
array
 &#39;title&#39; => string &#39;Forty What?&#39; (length=11)
 &#39;from&#39; => string &#39;Joe&#39; (length=3)
 &#39;to&#39; => string &#39;Jane&#39; (length=4)
 &#39;body&#39; => string &#39;
 I know that&#39;s the answer -- but what&#39;s the question?
 &#39; (length=57)
Copy after login

Summary: The above is this article The entire content, I hope it will be helpful to everyone's study.

Related recommendations:

How PHP implements the data paging display function

The subclass in PHP overrides the parent class Method (parent:: method name)

PHP method to operate MongoDB and simple analysis

The above is the detailed content of PHP method and example code for converting XML into array. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!