PHP transforms an XML document into an array using simplexml parsing

Source: Internet
Author: User
Tags addchild

XML is designed to transmit data rather than display it. Because of the need to read the data. We are usually very familiar with the operation of the array we can parse the XML as an array processing.

<?xml version= "1.0" encoding= "Utf-8"?>
<books>
<item>
<title> three countries </title>
<price>30.33</price>
<author>
<name> Li Jian </name>
</author>
</item>
<item>
<title> West Tour </title>
<price>25.55</price>
<author>lijian</author>
</item>
<item>
<title> Red Dream </title>
<price>14.44</price>
<author>lijian</author>
</item>
</books>

Here is the PHP content

<?php
Read XML
$xml =simplexml_load_file ("2.xml");
Print_r ($xml);
function ToArray ($sim) {
$arr = (array) $sim;
foreach ($arr as $k = = $v) {
if ($v instanceof simplexmlelement | | is_array ($V)) {//can be changed to Is_object ($V)
$arr [$k] = ToArray ($v);
}
}
return $arr;
}
$arr = ToArray ($xml);
Print_r ($arr);
Exit

Here is another method of rotating arrays

<?php
$xml = simplexml_load_file (' 2.xml ');
$xml = Json_decode (Json_encode ($xml), true);
Print_r ($xml);
Exit

Array back to XML mode

<?php

$arr = Array (
' Item ' =
Array (
0 =
Array (
' Title ' = ' Three Kingdoms ',
' Price ' = ' 30.33 ',
' Author ' =
Array (
' Name ' = ' Li Jian ',
),
),
1 =
Array (
' Title ' = ' West Tour ',
' Price ' = ' 25.55 ',
' Author ' = ' Lijian ',
),
2 =
Array (
' Title ' = ' Red Dream ',
' Price ' = ' 14.44 ',
' Author ' = ' Lijian ',
),
),
);
function Arr2xml ($arr, $node =null) {
if ($node = = = null) {
$simxml = new SimpleXMLElement (' <?xml version= "1.0" encoding= "Utf-8"?><root></root> ");
}else{
$simxml = $node;
}
foreach ($arr as $k = = $v) {
if (Is_numeric ($k)) {
$k = ' item ';
}
if (Is_array ($v)) {
Arr2xml ($v, $simxml->addchild ($k));
}else{
$simxml->addchild ($k, $v);
}
}
return $simxml->savexml ();
}
Header (' Content-type:text/xml ');
echo Arr2xml ($arr);

Exit

PHP uses SimpleXML to parse an XML document to convert it to an array

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.