Sorting xml with simpleXML/xpath?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
RustyDoorknobs
Forum Newbie
Posts: 15
Joined: Mon Sep 07, 2009 4:50 pm

Sorting xml with simpleXML/xpath?

Post by RustyDoorknobs »

Hey,

I have some xml, say:

Code: Select all

<Background>
 <Uses>14</Uses>
</Background>
<Background>
 <Uses>19</Uses>
</Background>
<Background>
 <Uses>3</Uses>
</Background>
How can I sort the xml from lowest Uses to highest?

Maybe an xpath expression?

Also, how could I just retrieve the bottom 2 Backgrounds, or the ones most recently added?

Thanks
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: Sorting xml with simpleXML/xpath?

Post by Weirdan »

RustyDoorknobs wrote: How can I sort the xml from lowest Uses to highest?
You can't sort using xpath alone - you can fetch your nodes into php arrays and sort those though.
Also, how could I just retrieve the bottom 2 Backgrounds,

Code: Select all

//Background[position()>last()-2]
or the ones most recently added?
There's no way to detect this given the xml you posted.

The bigger question, though, is why you're trying to use xml where database would be a natural choice?
Post Reply