Reputation: 885
I have an XML file and parse it into my PHP document. I want to order the child nodes of my XML in an alphabetical order and show them in my select box. Can someone please help me? I'm stuck in the sorting process... :)
country.xml
<?xml version="1.0"?>
<countries>
<country>
<name>Deutschland</name>
<league>Bundesliga</league>
</country>
<country>
<name>Frankreich</name>
<league>Ligue 1</league>
</country>
<country>
<name>Osterreich</name>
<league>Tipp3-Bundesliga</league>
</country>
<country>
<name>England</name>
<league>Premier League</league>
</country>
<country>
<name>Schweden</name>
<league>Allsvenskan</league>
</country>
<country>
<name>Kanada</name>
<league>Canadian Soccer League</league>
</country>
</countries>
My PHP code looks as follows:
echo "<select>";
foreach ($newXml as $item) {
$country=$item->name;
$league=$item->league;
echo $league;
echo "<option>".$country."-".$league."</option>";
}
echo "</select>";
Upvotes: 0
Views: 2036
Reputation: 173562
You can do this in three steps:
// 1. collect
foreach ($newXml as $country) {
$items[] = "{$country->name} - {$country->league}";
}
// 2. sort (on country and league in this case)
sort($items);
// 3. enumerate
echo '<select>';
foreach ($items as $item) {
echo '<option>', htmlspecialchars($item), '</option>';
}
echo '</select>';
Upvotes: 1
Reputation: 964
You can use array before creating a select box.
echo "<select>";
$temp = array()
foreach ($newXml as $item)
$temp [$item->name] = $item->league;
ksort($temp);
foreach ($teml as $name => $league) {
$country=$name;
$league=$league;
echo $league;
echo "<option>".$country."-".$league."</option>";
}
echo "</select>";
Its a blind shot... should work.
Upvotes: 0