Sort a group of nodes by attribute? How?

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

I have the following XML file:

<?xml version="1.0" encoding="iso-8859-1"?>
  <item line="2">all that glitters is gold,</item>
  <item line="1">Theres a lady thats sure,</item>
  <item line="3">and she's buying a stairway to heaven</item>

To output this code Im using the following PHP:

$xmldoc = domxml_open_file('stairway.xml',
$node = $xmldoc->document_element();
if ($xmldoc->has_child_nodes()) {
  $node = $node->first_child();
  $endwhile = false;
  while ($endwhile != true) {
    echo $node->get_content() . "<br />";
    if ($node->next_sibling()) {
      $node = $node->next_sibling();
      $endwhile = true;

This does what it supposed to do except I want to ensure that it
outputs nodes ordered by 'line' attribute. The obvious answer would be
to put them in order in the XML file and the above example is very
simple so that you get the point, the real life example however will be
much larger and encase anyone put something in the wrong order it would
muck up my presentation. How could I adapt my code above to allow my
nodes to be sorted? I dont mind the nodes being out of order in the
physical file (stairway.xml) but when they are output using my script,
I want them to be ordered.



Re: Sort a group of nodes by attribute? How?

How about if I entered the node value and the date attribute into a
multi-dimensional array and sorted and then sorted it by date? I dont
really know a great deal about multi-dimensional arrays but ill get

I understand that it could probably be done using xslt but thats a step
ahead of me yet.

I thought that their would have been an easier way as when you xmldom
read from a xml file it creates a virtual xml tree where nodes can be
added, removed, updated and I figured even sorted before being
re-written to the xml file (if required).

Anyway, Ill probably just get onto the array idea. Thats should do it.
Please give comment if you know a better way or any suggestions on my
above idea. Thanks


Site Timeline