Sorting SimpleXML Entries by Single Key

Given the following XML that has been loaded into a SimpleXML object in PHP:

To sort by name, do the following:

To sort by city, do the following:

This is a simple technique that works when you have a single key by which you wish to sort the XML. We create the $data array and associate the key (name in the former case, city in the latter) with the actual element, and let ksort take care of the rest. ksort sorts an array by the key while maintaining the association.

Motivation

The reason for this post is that while Googling I kept finding more complex solutions which included usort with a custom compare function, or array_multisort which was even more complex, or using a third party implementation like SimpleDOM. This was much simpler and quicker, and I wanted to record this for future use.

Leave a Reply