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

Example Interest Rates: Home Loan Variable: 1.89% (1.9%*) • Home Loan Fixed: 1.84% (2.11%*) • Fixed: 1.84% (2.11%*) • Variable: 1.89% (1.9%*) • Investment IO: 2.05% (4.36%*) • Investment PI: 1.58% (2.72%*)

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.

  AUS Eastern Standard Time (Washington)

  Want to have a chat?
 

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