How to convert XML to array in PHP

高洛峰
Release: 2023-03-04 06:10:02
Original
1373 people have browsed it

If you use curl to get the xml data
xml=simplexmlloadstring(data);
data[′tk′]=jsondecode(jsonencode(xml),TRUE);
If you get the URL data directly
xml=simplexmlloadfile(data) ;
data[′tk′]=jsondecode(jsonencode(xml),TRUE);
First convert the simplexml object into json, and then convert the json into an 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

The above is the entire content of this article, I hope it will be helpful to everyone’s learning.


For more articles related to how PHP converts XML into an array, please pay attention to the PHP Chinese website!


Related labels:
xml
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!