Australia's Leading Digital Marketing Experts. T. 1300 235 433  |  Aggregation Enquires Welcome

Convert XML File to Array With PHP

I was once an advocate for XML data because of its readability. However, that comes with an overhead, and its more difficult to deal with programmatically. If you have an XML file, the following function will convert it into a PHP array. It won't support all nested attributes - that function is forthcoming.

1
<?php 
2
/*
3
 Convert XML File to Array With PHP
4
 https://www.beliefmedia.com.au/code/php-snippets/xml-file-to-array
5
 
6
*/
7
 
8
function beliefmedia_xml_to_array($xml_path) {
9
 
10
  $xml = @file_get_contents($xml_path);
11
  if ($xml === false) return 'Error';
12
 
13
  $xml = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
14
  $json = json_encode($xml);
15
  $array = json_decode($json, TRUE);
16
 
17
 return (array) $array;
18
}

Usage is easy:

1
<?php 
2
$xml_path = 'your-xml-file.xml';
3
$array = beliefmedia_xml_to_array($xml_path);
4
 
5
/* To return to screen (fill in the pre tags) */
6
echo print_r($array, true);

Like this article?

Share on facebook
Share on Facebook
Share on twitter
Share on Twitter
Share on linkedin
Share on Linkdin
Share on pinterest
Share on Pinterest

Leave a comment