Convert XML to Array in PHP usingĀ SimpleXML
Though I would suggest using DomDocument for parsing XML strings and files in PHP, here is an example of converting XML to an Array in PHP using SimpleXML method. The SimpleXML extension in PHP provides a very simple and easily usable toolset to convert XML to an object that can be processed with normal property selectors and array iterators.
The code I have posted below traverse through all the child nodes of the XML up to the deepest level and forms an array in the same structure. It takes care of the CDATA tags as well, that you get the text defined inside the CDATA tag. One thing this code doesn’t do is parsing the attributes. This code will avoid the attributes in a tag. You can just easily add this feature yourself by using the “attributes” method of SimpleXML.
<?php
$xmlData = "<FileInfo>
<File>
<Name id='4'><![CDATA[Test.txt]]></Name>
<MD5>c63f02d0fee180d1b0e1f49cb52edba3</MD5>
<LastModified>2008-09-05T14:42:44.000 01:00</LastModified>
<Path><![CDATA[/Users/haat/Desktop/Test folder/carriage_rets.txt]]></Path>
<Size>181</Size>
</File>
<File>
<Name id='4'>My.jpg</Name>
<MD5>c63f02d0fee180d1b0e1f49cb52edba3</MD5>
<LastModified>2008-09-05T14:42:44.000 01:00</LastModified>
<Path><![CDATA[/Users/haat/Desktop/Test folder/carriage_rets.txt]]></Path>
<Size>181</Size>
</File>
</FileInfo>";
function xmlToArray($input, $callback = null, $recurse = false) {
$data = ((!$recurse) && is_string($input))? simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA): $input;
if ($data instanceof SimpleXMLElement) $data = (array) $data;
if (is_array($data)) foreach ($data as &$item) $item = xmlToArray($item, $callback, true);
return (!is_array($data) && is_callable($callback))? call_user_func($callback, $data): $data;
}
$fileinfo_array = xmlToArray($xmlData);
echo "<pre>";
print_r($fileinfo_array);
echo "</pre>";
?>
And this is the output you would get:
Array
(
[File] => Array
(
[0] => Array
(
[Name] => Test.txt
[MD5] => c63f02d0fee180d1b0e1f49cb52edba3
[LastModified] => 2008-09-05T14:42:44.000 01:00
[Path] => /Users/haat/Desktop/Test folder/carriage_rets.txt
[Size] => 181
)
[1] => Array
(
[Name] => My.jpg
[MD5] => c63f02d0fee180d1b0e1f49cb52edba3
[LastModified] => 2008-09-05T14:42:44.000 01:00
[Path] => /Users/haat/Desktop/Test folder/carriage_rets.txt
[Size] => 181
)
)
)
The above code uses “simplexml_load_string” to load an XML string to parse. If you need to load an XML file and parse, you could use “simplexml_load_file”.
Just run the PHP code and play around. Ask me if you have any questions.
ASK a Question! |
|

Thank you, works like a charm!
Great to know. You are welcome.