SimplePie RSS class and CodeIgniter

Posted in: Website Development

by Fiaz Khan (Technical Director)

Users of the latest version of Simplepie (Version 1.0.1) have been getting errors when passing in the feed url. The error refers to a missing method "feed_url()". This is due to a change in Simplepie, to set the feed url you must now use "set_feed_url(your rss url)".

A pet project of mine which I will unleash upon you all soon required the home page to read in an RSS feed. Since I am a CodeIgniter whore I soon learnt that amongst its many libraries and helpers that there wasn't an RSS reader.

This was easily solved using an open source PHP RSS class called SimplePie. Simply, I can't imagine ever needing anything else. Not to mention the ease of getting it to work within CodeIgniter. By placing simplepie.inc in the libraries directory and renaming it to simplepie.php, I could now use its methods to parse and display my RSS feed.

Within your controller:

function index() {
    $this->load->library('simplepie');
        //$this->simplepie->feed_url('http://www.digg.com/rss/indexdig.xml');
        // You may have encountered an error where it couldn't find feed_url. This is due
        // to a change in the latest version of simplepie. Simply, feed_url is now set_feed_url
        $this->simplepie->set_feed_url('http://www.digg.com/rss/indexdig.xml');
        $this->simplepie->init();
        $data['dig_feed'] = $this->simplepie;
}
?>

Passing the $data array holding the parsed feed data to the view template made displaying the data a breeze. get_items() returns all feed data as an array. Optionally, if you wish to only display the first 5 items, get_items takes 2 parameters, the starting position and quantity to return. Passing in 0,5 as arguments returns the first 5 items.

foreach($dig_feed->get_items() as $item) {
     echo $item->get_title() . '
';
}
?>

Any problems, let me know.