Search code examples
phpxmlsortingalphabetical

Sort XML rows alphabetically by one node, using PHP


This is an example of my XML:

<ROW>
<DEPT_CODE>11111</DEPT_CODE>
<DEPARTMENT>Program Name</DEPARTMENT>
<BLDG_CODE>BLCG</BLDG_CODE>
<ADDR_STREET1>123 Main Street</ADDR_STREET1>
<ADDR_STREET2>Suite 456</ADDR_STREET2>
<ADDR_STREET3>Lower Level</ADDR_STREET3>
<ADDR_CITY>New York</ADDR_CITY>
<ADDR_STATE>NY</ADDR_STATE>
<ADDR_ZIP>101010</ADDR_ZIP>
<PHONE>212-555-1234</PHONE>
<FAX>212-555-5678</FAX>
<EMAIL>[email protected]</EMAIL>
<URL>http://www.company.com</URL>
</ROW>

This is my PHP:

<?php
$xml = simplexml_load_file('department.xml');
foreach($xml->children() as $depts) {
echo $depts->DEPARTMENT . "<br />";
}
?>

It correctly outputs the list of departments, in the order they appear in the XML, but I want it to sort alpha by DEPARTMENT node.


Solution

  • All of the above answers seemed to show a piece of what I ended up with, but I'm adding the final results in case it's helpful to someone else:

    $xml = simplexml_load_file('data.xml');
    foreach($xml->children() as $departments) {
        (string)$collect[(string)$departments->DEPT_NAME]=$departments;
    }
    
    usort ($collect, function($a, $b) {
        return strcmp($a->DEPT_NAME, $b->DEPT_NAME);
    });
    
    echo "<ul>";
        foreach($collect as $departments) {
            if ($departments->DEPT_NAME != "") {
                echo "<li>" . $departments->DEPT_NAME . "</li>";
            }
        }
    echo "</ul>";