0

I am new this parsing xml feeds; so I have a piece of code that I have been working on that extracts the data from the xml file. Now I want be able to sort the array by the publish date pubdate. I have not found any examples that can anyone help me.

I used sort() which puts it in some random order.

$xml_headline_key = "*ARRAY*CATCHUP*PROGRAMMENAME";
$xml_link_key = "*ARRAY*CATCHUP*ITEMURL";
$xml_description_key = "*ARRAY*CATCHUP*SHORTSYNOPSIS";
$xml_publish_key = "*ARRAY*CATCHUP*ORIGINALAIRINGDATE";
$story_array = array();
$counter = 0;
class xml_story{
 var $headline, $description, $link, $pubdate;
}
function contents($parser, $data){
 global $current_tag, $xml_headline_key, $xml_link_key, $xml_description_key, $counter, $story_array, $xml_link_key, $xml_publish_key;
 switch($current_tag){
  case $xml_headline_key:
   $story_array[$counter] = new xml_story();
   $story_array[$counter]->headline = $data;
   break;
  case $xml_link_key:
   $story_array[$counter]->link = $data;
  break;
  case $xml_description_key:
   $story_array[$counter]->description = $data;
   $counter++;
   break;
  case $xml_publish_key:
   $story_array[$counter]->pubdate = $data;
  break;
  }
}

$corrie_counter = 0;
sort($story_array);
$dateformat = "D j M, g:ia";

for($x=0;$x<count($story_array);$x++){
 if($story_array[$x]->headline == "Coronation Street"){
 if($corrie_counter != 4){
 echo "<li><span class=\"bold\">". date($dateformat, strtotime($story_array[$x]->pubdate)) . "</span>\n";
echo "\t<span class=\"text\">" . trunc($story_array[$x]->description,30, " ") . "</span>\n";

echo "\t"; $corrie_counter++; } } }

2
  • If you want to save some time, I would highly recommend the magpie rss parser. magpierss.sourceforge.net Commented Nov 19, 2009 at 12:18
  • @shane this does look like rss but xml !== rss Commented Nov 19, 2009 at 13:12

1 Answer 1

2

You can use uasort, and inside sortByPubdate define the way the two pubdates should be compared.

uasort($story_array, 'sortByPubdate');
// Sort function
function sortByPubdate($a, $b) {
    if ($a->pubdate == $b->pubdate) {
        return 0;
    }
    return ($a->pubdate < $b->pubdate) ? -1 : 1;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it didn't work the content is the same as before, actually the sort(); actually sorted more than the uasort. Is there something else I need to add with uasort am I missing something???? Oh yeah I included it just above the for loop.
Is possible the $story_array is already sorted by date? Just try to order it by a different field (maybe the headline). Also take a look to the documentation php.net/manual/en/function.uasort.php

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.