1

i searched through the website and couldnt find exact result for my question.

i need to search through the xml file and sort the output by the order in date descending.

<?xml version="1.0"?>
<entries>
  <entry>
    <date>1299565881</date>
    <action>made an action under category</action>
    <user>Admin</user>
  </entry>
  <entry>
    <date>1299566115</date>
    <action>Item deleted</action>
    <user>Admin</user>
  </entry>
</entries>

here is my code

<?php

$data = simplexml_load_file($filename);

if($to_date_int>$global_date)
    $op = $data->xpath('/entries/entry[date<='.$to_date_int.']');
else
    $op = $data->xpath('/entries/entry');

Thanks in advance..

2
  • What kind of output are you expecting? You want to sort each entry by date, then what? Commented Sep 28, 2011 at 5:52
  • XPath is not a good tool for sorting, either pre-sort with XSLT or post-sort with PHP. Commented Sep 28, 2011 at 6:31

1 Answer 1

3

Since $op will be an array of the matching entry elements, you could use PHP's array sorting functions to sort by their associated date elements.

function sort_entries_by_date($a, $b) {
    return (int) $b->date - (int) $a->date;
}
usort($op, 'sort_entries_by_date');

(If you're using PHP 5.3, the named function could be placed by an inline anonymous function.)

Sign up to request clarification or add additional context in comments.

2 Comments

Works fine., thank u salathe., Can u explain me how does the function actually works !? what happens in the line return (int)$b->date - (int)$a->date; Thanks again.
The sort function must return 0 if the values are to be considered the same, less than zero if $a is to appear lower than $b in the sorted array, or greater than zero otherwise ($a will appear higher than $b). So my function will sort the entries by descending date order (because if the date in $a is greater than that in $b, the function will return a negative number). As for the maybe strange (int)$b->date syntax, that's just getting the integer value of the <date> element belonging to the <entry> held in $b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.