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