RBA Cash Rate: 4.35% · 1AUD = 0.67 USD · Inflation: 4.1%  
Leading Digital Marketing Experts | 1300 235 433 | Aggregation Enquires Welcome | Book Appointment
Example Interest Rates: Home Loan Variable: 5.20% (5.24%*) • Home Loan Fixed: 5.48% (6.24%*) • Fixed: 5.48% (6.24%*) • Variable: 5.20% (5.24%*) • Investment IO: 5.78% (6.81%*) • Investment PI: 5.49% (6.32%*)

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);

Download our 650-page guide on Finance Marketing. We'll show you exactly how we generate Billions in volume for our clients.

  E. Australia Standard Time [ UTC+10, Default ] [ CHECK TO CHANGE ]

  Want to have a chat?
 

Like this article?

Share on Facebook
Share on Twitter
Share on Linkdin
Share on Pinterest

Leave a comment