Friday, 13 July 2012

OOP PHP RSS Reader

This is a simple RSS Reader which allows you to add multiple feeds. It also sorts the results before returning them to the calling page.
The calling page would look something like this:


<?php
require_once 'rss.class.php';
$addr1 = 'http://feeds.bbci.co.uk/sport/0/football/rss.xml';
$addr2 = 'http://feeds.howtogeek.com/HowToGeek';
$addr3 = 'http://feeds.feedburner.com/TheEdTechie';
$rss = new rss;
$rss->addFeed($addr1);
$rss->addFeed($addr2);
$rss->addFeed($addr3);
$arr = $rss->getFeed();
foreach($arr as $row)
{
echo $row->title.'-'.$row->pubDate.'<br />';
}
?>

So, here's the RSS Reader class:


<?php
class rss
{
public $addr = NULL;
private $outArr = Array();
function __construct($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
if($this->addr)
{
return $this->addFeed();
}
}


function addFeed($addr = NULL)
{
$this->addr = $addr != NULL ? $addr : $this->addr;
$rss = simplexml_load_file($this->addr);
$this->outArr = array_merge($this->outArr, $rss->xpath('/rss//item'));    
}


function getFeed()
{
usort($this->outArr, function ($x, $y)
{
if (strtotime($x->pubDate) == strtotime($y->pubDate)) return 0;
    return (strtotime($x->pubDate) > strtotime($y->pubDate)) ? -1 : 1;
});
return $this->outArr;
}
}
new rss;
?>

No comments:

Post a Comment