Sorting XML data in PHP

There are plenty of different ways of sorting XML in PHP, but for me this is the easiest way.

Take the sample XML file below which contains multiple vehicles.

<?xml version="1.0" standalone="yes"?>
<LIST>
  <VEHICLE>
    <YEAR>2003</YEAR>
    <MAKE>FORD</MAKE>
    <MODEL>FOCUS</MODEL>
  </VEHICLE>
  <VEHICLE>
    <YEAR>2004</YEAR>
    <MAKE>AUDI</MAKE>
    <MODEL>A3</MODEL>
  </VEHICLE>
  ...
</LIST

You could load the XML and loop through it to create an array using a FOREACH loop but it is easier and probably quicker to encode the data as JSON and then decode it which will produce an array in a single line of code without the worry of naming the elements in the array:

$xml 	= simplexml_load_file("cars.xml");
$items 	= $xml->xpath("LIST/VEHICLE");
$cars   = json_decode(json_encode($items),true);

Then all you have to do is sort the array specifying the field to sort and the type of sort:

array_multisort(array_column($cars,'YEAR'),SORT_ASC,SORT_NUMERIC,$cars);

Finally the last step is a simple output to screen:

foreach($cars as $i)
	echo "<p>".$i["YEAR"]." - ".".$i["MAKE"]." - ".$i["MODEL"]."</p>";

We'd love to hear from you!

If you think Bronco has the skills to take your business forward then what are you waiting for?

Get in Touch Today!

Discussion

Add a Comment

Get in touch