Search code examples
phpxmlrsssimplexml

(Date / Time) checker for XML Feed not returning a valid result


I'm trying to debug an emergency alert script. It should be checking to see if the XML item is less than '40000000000' seconds old and echo 'Its been less than 24 hours'. I set it to a crazy high number and it's still returning "else".

<?php

$xml=simplexml_load_file("https://content.getrave.com/rss/harpercollege/channel1");
foreach($xml->channel->item as $child)
{
    unset($titleVal, $descriptionVal, $pubdate, $dateString);
    $titleVal = (string)$child->title;
    $descriptionVal = (string)$child->description;
    $pubDate = (string)$child->pubDate;
    $pubDate= date("D, d M Y H:i:s T", strtotime($pubDate));  
    echo $titleVal . "<br>" . $descriptionVal . "<br>" . $pubDate . "<br>";
    if($pubDate > time() + 40000000000) {
        echo 'Its been less than 24 hours';
    } else {
        echo '24 Hours have passed';
    }

} 
?>

Solution

  • The file you are using has a <pubDate>Fri, 29 Oct 2021 13:25:47 GMT</pubDate> So, for testing purposes fake a sensible date so you know what should be happening, then you dont have to change the code to do riduculous things and you are actually testing in a real situation and wont have to amend the code to work properly with real data! Never a good idea!!!

    $xml=simplexml_load_file("https://content.getrave.com/rss/harpercollege/channel1");
    foreach($xml->channel->item as $child)
    {
        unset($titleVal, $descriptionVal, $pubdate, $dateString);
        $titleVal = (string)$child->title;
        $descriptionVal = (string)$child->description;
        $pubDate = (string)$child->pubDate;
        $pubDate= date("D, d M Y H:i:s T", strtotime($pubDate));  
    
        ### Uncomment one or the other of these KNOWN dates    
        # fake a sensible date time less than 24 hours old
        #$pubDate= 'Wed, 19 Oct 2022 13:25:47 GMT';  
        
        # fake a sensible date time GRETAER than 24 hours old
        $pubDate= 'Tue, 18 Oct 2022 13:25:47 GMT';  
        
        #convert it to a timestamp (compare apples and apples and not apples and oranges)
        $pubDate = strtotime($pubDate);
     
        # Test the pubDate against NOW, time() MINUS 1 day (24*60*60)
        # Test the pub date is Greater that now minus a days worth of seconds
        if($pubDate > time() - 24*60*60) {
            echo 'Its been less than 24 hours';
        } else {
            echo '24 Hours have passed';
        }
    }