A week ago I posted about using PHP to display an RSS feed. We moved to a new server that did not have DOM enabled, so I have updated my code to use curl instead of DOMDocument. Either method does work, but this is nice and clean. See below for my new code:
<html>
<head>
<link rel="stylesheet" href="/alert-rss.css" media="all">
</head>
<body>
<?php
//set timezone
date_default_timezone_set('America/New_York');
//set RSS feed
$handle = curl_init('https://url-of-rss-feed.com');
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($handle, CURLOPT_ENCODING, 'identity');
//get RSS feed from $handle
$response = curl_exec($handle);
curl_close($handle);
$xml = simplexml_load_string($response, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$data = json_decode($json, true);
//load feed
$feeds = array();
//load only required feed items
if(isset($data['channel']['item'])) {
foreach($data['channel']['item'] as $item) {
$feeds[] = array(
'title' => $item['title'],
'desc' => $item['description'],
'date' => $item['pubDate'],
);
}
}
//set the internal point of the array to last element
end($feeds);
//pull key of array at pointer so we only display one entry
$key = key($feeds);
//set variables to display data from array
$title = $feeds[$key]['title'];
$description = $feeds[$key]['desc'];
$date = date('l F d, Y g:ia', strtotime($feeds[$key]['date']));
//set $end_date for when RSS expires - calculation entered as (hours*secondsperhour)
$end_date = date('l F d, Y H:i', strtotime($feeds[$key]['date']) + (18*3600));
//set how date variables are calculated for comparison purposes
$today = date('l F d, Y H:i');
$today_calc = strtotime($today);
$end_date_calc = strtotime($end_date);
//display what we have found if it is current
if($today_calc < $end_date_calc) {
echo '<div id="blinky-div"><p><strong>'.$title.'</strong><br />';
echo '<small><em>Posted on '.$date.'</em></small></p>';
echo '<p>'.$description.'</p></div>';
//hide div if there is no current data
} else {
echo '<div style="display: none;">No current RSS</div>';
}
?>
</body>
</html>
