Build an RSS 2.0 Feed with CodeIgniter

Build an RSS 2.0 Feed with CodeIgniter

In this tutorial, we will build a RSS 2.0 Feed with the PHP framework CodeIgniter. After this tutorial, you will be able to build a feed for any custom website in no time at all.

Tutorial Details

  • Program: CodeIgniter PHP Framework
  • Version: 1.7.1
  • Difficulty: Easy
  • Estimated Completion Time: 30 minutes

Step 1: What we Need

Finished Product

First, we’ll take a look at the tools needed to get started. Besides an installation of CodeIgniter, we need a running MySQL database with some content from which we can build our feed.

For this purpose, here are some dummy entries you can import. Create a database called tut_feeds. Then, copy the following code, and import it into your MySQL database.

    CREATE TABLE IF NOT EXISTS `posts` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `title` varchar(120) NOT NULL,
      `text` text NOT NULL,
      `date` date NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=MyISAM;
    
    INSERT INTO `posts` (`id`, `title`, `text`, `date`) VALUES
    (1, 'Some great article', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10'),
    (2, 'Another great article', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10'),
    (3, 'News from myfeed', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).', '2009-08-10');

This is how it should appear in phpmyadmin. After you have pasted the code in, press the Ok button on the right side.

If everything works correctly, you should see have something like this:

Step 2: Setting up CodeIgniter

Before we start writing code, we need to configure CodeIgniter.

Browse to your CI folder, and then into system/application/config. We will need to edit the following files:

  • autoload.php
  • config.php
  • database.php
  • routes.php

Edit the autoload.php like so:

	$autoload['libraries'] = array('database');

This will tell CI to load the database automatically; so we don’t need to load it every time.

Edit the config.php like so:

	$config['base_url'] = "http://localhost/YOUR DIRECTORY";

You need to replace tutorials/ci_feeds with your directory and CI folder.

Edit the database.php like so:

	$db['default']['hostname'] = "localhost"; // your host
    $db['default']['username'] = "root";
    $db['default']['password'] = "";
    $db['default']['database'] = "tut_feeds"; 

With these settings, we tell CI which database to use. Here you also have to replace hostname, username and
password with your personal database info.

Edit the routes.php like this:

	$route['default_controller'] = "Feed"; 

The default controller is the “index” controller for your application. Every time you open
localhost/YOUR DIRECTORY, this default controller will be loaded first. We’ll create the feed in the next step.

Step 3: Creating the Feed Controller

In this controller, all the magic happens. Browse to system/application/controllers and create a new file
called feed.php. Next, create the Feed controller and have it extend the parent CI Controller.

	class Feed extends Controller {
      
      function Feed()
      {
		parent::Controller();
      }
}

If you are already confused please have a look at Jeffrey’s
Easy Development with CodeIgniter tutorial.
After you’ve learned the basics, return to continue this tutorial! :)

Before the next step, we’ll make use of CI’s great helpers. Load the xml and text helper.

class Feed extends Controller {
      
      function Feed()
      {
        parent::Controller();
        
        $this->load->helper('xml');
		$this->load->helper('text');
      }
}

Step 4: Creating the Model

Next, will create a model to receive data from the database. If you don’t know what models are, have a look at the CI
userguide. Browse to system/application/models
and create a file called posts_model.php.

class Posts_model extends Model {
	
	// get all postings
	function getPosts($limit = NULL)
	{
		return $this->db->get('posts', $limit);
	}
}

We are using active records to receive data
from the database. The first parameter declares the table we want to use and with the second we can set a limit – so we
can tell CI how many records we want to retrieve.

Perhaps you’ve noticed that $limit is set to NULL by default. This makes it possible to set a limit, but you don’t have to.
If you don’t set a second parameter, this function will simply return all records.

Step 5: Back to the Feed Controller

Now that we’ve created our model, we can continue with our feed controller. We’ll load the posts_model that we just created.

class Feed extends Controller {
      
      function Feed()
      {
        parent::Controller();
        
        $this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
      }
}

With the second parameter, we assign our model to a different object name – so we have less to type :P. Now we create the index
method which is the method called by default. Let’s set up some information for the feed view later too.

	function index()
	{
		$data['feed_name'] = 'MyWebsite.com'; // your website
		$data['encoding'] = 'utf-8'; // the encoding
        $data['feed_url'] = 'http://www.MyWebsite.com/feed'; // the url to your feed
        $data['page_description'] = 'What my site is about comes here'; // some description
        $data['page_language'] = 'en-en'; // the language
        $data['creator_email'] = 'mail@me.com'; // your email
        $data['posts'] = $this->posts->getPosts(10);  
        header("Content-Type: application/rss+xml"); // important!
	}

While the majority of the information above is easy to understand, we will have a look at two of them.
header(“Content-Type: application/rss+xml”); is a very important part. This tells the browser to parse it as
an RSS Feed. Otherwise the browser will try to parse it as plain text or html.

With $data['posts'] = $this->posts->getPosts(10); we are using our model and are storing all records in the $posts array.
I set the limit to 10; so it will return, at most, 10 records. You can set this value higher or lower if you want. If we leave it
blank, like $data['posts'] = $this->posts->getPosts();, it would return all records.

Finally, we need to load the view which we will create in the next step.

	function index()
	{
		$data['feed_name'] = 'MyWebsite.com'; 
		$data['encoding'] = 'utf-8'; // the encoding
        $data['feed_url'] = 'http://www.MyWebsite.com/feed'; 
        $data['page_description'] = 'What my site is about comes here'; 
        $data['page_language'] = 'en-en'; 
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);  
        header("Content-Type: application/rss+xml"); 
        
        $this->load->view('rss', $data);
	}

Our $data array is passed as the second parameter to the view file, so we can access it in the view.
Your feed controller should now look like this:

class Feed extends Controller {
	
	function Feed()
	{
		parent::Controller();
		
		$this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
	}
	
	function index()
	{
		$data['feed_name'] = 'MyWebsite.com';
		$data['encoding'] = 'utf-8';
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
        $data['page_description'] = 'What my site is about comes here';
        $data['page_language'] = 'en-en';
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);    
        header("Content-Type: application/rss+xml");
		
		$this->load->view('rss', $data);
	}
	
}

Step 6: Creating the View

Finally we have to create the view file – our output. Browse to system/application/views and crate a file called
rss.php.

First we set the xml version and the encoding within the head.

	<?php  echo '<?xml version="1.0" encoding="' . $encoding . '"?>' . "\n"; ?>

Followed by some rss meta information.

    
    
        

Now we will access the array $data from the previous step. We can access this data via the array keys, like so:

    

    
    
    
    

    Copyright 
    

Now we need to loop, with foreach, to get all records.

    result() as $post): ?>
    
       

          
          id) ?>
          id) ?>

          	text, 200); ?> ]]>
			date; ?>
        

        
    
	
    	
	<  

For link and guide, you have to set a link to your controller where the posts are fetched. For example: my/posts/$post->id.

I hope you noticed CDATA. This is used for text-output (content). Remember how we learned in the head that this is xml;
so it has to be xml valid. If we don’t set CDATA we’ll potentially end up with invalid markup.

Step 7: Overview

Now your files should look like this:

system/application/controllers/feed.php

class Feed extends Controller {
	
	function Feed()
	{
		parent::Controller();
		
		$this->load->helper('xml');
		$this->load->helper('text');
        $this->load->model('posts_model', 'posts');
	}
	
	function index()
	{
		$data['feed_name'] = 'MyWebsite.com';
		$data['encoding'] = 'utf-8';
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
        $data['page_description'] = 'What my site is about comes here';
        $data['page_language'] = 'en-en';
        $data['creator_email'] = 'mail@me.com';
        $data['posts'] = $this->posts->getPosts(10);    
        header("Content-Type: application/rss+xml");
		
		$this->load->view('rss', $data);
	}
	
}

system/application/models/posts_model.php

class Posts_model extends Model {
	
	// get all postings
	function getPosts($limit = NULL)
	{
		return $this->db->get('posts', $limit);
	}
}

system/application/views/rss.php

	' . "\n"; ?>
    
    
        
        
        
    
        
        
        
        
    
        Copyright 
        
    
        result() as $post): ?>
        
            
    
              
              id) ?>
              id) ?>
    
                text, 200); ?> ]]>
                date; ?>
            
    
            
        
        
        
      

And our feed looks like this, just with other content :)

Conclusion

I hope you’ve learned how easy it is to build an RSS 2.0 Feed with the power of CodeIgniter. For more tutorials and screencasts on CodeIgniter, check out Jeffrey`s CodeIgniter from Scratch series.


Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Sergio

    Awesome, need to try this out.

  • http://www.quizzpot.com Crysfel

    there is a problem with the view, i think you should change the “” to “>” and “<” in your post.

    Thanks for the tut :D

  • http://www.imblog.info Muhammad Adnan

    seems I should try CI framework.

  • BhenChod

    Would be better to show how we can create a twitterfeed of our own. eg. post to twitter from RSS, and works with all feeds.

  • http://www.designfollow.com/ designfollow

    great info

    thank you

  • http://blog.davidrojas.net David Rojas

    Now that’s a useful tutorial. Thanks. But please fix the view, I think the wp plugin for showing code has screwed it up.

    • http://www.newarts.at Drazen Mokic
      Author

      I cant do anything now, Jeffrey can fix this :)

  • Jonas

    CodeIgniter is great – my preferred PHP framework. Zend Framework really makes something as simple as MVC complicated and time-consuming, whereas it’s easy with CodeIgniter. For those who are interested in getting further into CodeIgniter, check out http://codeigniter.com/tutorials/ .

  • http://vector.laroouse.com esranull

    really useful post but I cant

  • Zoran

    Derek Allard, one of the guys from CI already has done this long time ago and there are other tutorials like this one, but anyhow, thank you very much for your effort, i am an experienced CI user and i am always happy to see tutorial about it.

  • http://www.posetibac.info Milan

    That is really simple I tought that there will be more work.

    Great tut Drazene. Thanks.

  • http://www.mimrankhan.com Imran Khan

    CI KICK ASS FOR PHP , nice tutorial

  • http://qvister.se Anton Lindqvist

    Great tutorial!
    But wouldn’t it be more efficient to use CI:s own Output class to set the Content-Type header? See example below.

    $this->output->set_header(‘Content-Type: application/rss+xml’);

    • http://www.newarts.at Drazen Mokic
      Author

      Yeah it maybe would be more efficient, you are right. CI has so much helpfull classes, helpers and libraries that i sometimes forget that there is this special one :D

      thanks

  • Matt B

    Fantastic tutorial! I will be sure to reference this one in the future.

    Jeff, PLEASE fix that formatting problem!

  • http://brianswebdesign.com Brian Temecula

    While this tutorial is very basic, I like the continued dedication to CodeIgniter. Thanks for your work.

  • Chalda

    Why you include xml helper if you don’t use the function xml_convert() ?

  • Commenter

    I see one problem with this tutorial
    “After this tutorial, you will be able to build a feed for any custom website in no time at all. ”

    CI is not needed for XML, though a tutorial like this is great if someone already has a website built in CI, if not then this is far from a practical solution.

    • http://brianswebdesign.com R. B. Gottier

      Isn’t it obvious? If you don’t use CI, then you are missing out! I just released an E-Commerce application to the CI Wiki. That wouldn’t be a practical application for somebody to use if they weren’t a CI user, but it should be obvious that CI is awesome. The benefits of this framework are many, and after reading many articles about CI, a developer should have at least checked out CI by now.

      • Commenter

        I just remembered this tutorial is aimed more at new people rather than experienced developers. But, put it this way, if they were taught to build an RSS feed in raw PHP, then they can very easily do so in CI without a tutorial.

      • Commenter

        Or better yet, teach some basic OOP and make a BASIC XML creator library with an RSS feed helper (all in same class), and that can then very easily be imported into CI, or any other framework for that matter, and thats much more pratical imo.

      • Robert P

        Of all the frameworks I have trialled over the years, CodeIgniter has the worst MVC implementation. It’s more a collection of poorly coded libraries loaded through a pointless interface.

        “The benefits of this framework are many”

        The benefits of any framework are many, but CI falls short at what it tries to imitate: a full-stack framework.

        Using CakePHP as an example (and not purposefully advocating it) you can build a more flexible RSS generator in about the same amount of time without needing to code the XML manually, as in this tutorial.

        Ultimately, use whichever framework gets the job done for you, but don’t try and claim CI is anything other than an inferior framework.

  • http://stevendobbelaere.be Steven Dobbelaere

    I had to make some xml structure adjustments to get it to work, but it works now. I did this in no time, that’s why I love codeigniter.

  • Rick

    Have you tried building an RSS feed in PHP without CodeIgniter? Because I think it’s probably much faster to write and to run without a web framework.

  • http://www.webmasterdubai.com webmasterdubai

    im big fan of CI, and this is really good tutorial fond to create feeds with CI in really simple way.

  • new2web

    I am new to CI, I get afatal error saying Fatal error: Call to undefined function site_url() when I execute the code. Please let me know how to solve this problem?

    • http://www.newarts.at Drazen Mokic
      Author

      You need to load the ‘url’ helper before using the site_url() function.

  • http://downloadebookfree.wordpress.com/ Jack Starr

    This is what i wanted….

  • http://tipsphotoshop.com tips photoshop

    very nice,thanks :)

  • troll

    please fix the code!!!
    thanks!

  • troll
  • Andy

    Shame on you, copied code, with event incomplete code.

  • http://www.newarts.at Drazen Mokic
    Author

    I can`t believe what you 2 guys are saying…

    It`s the same as you would say “tutsplus has stolen the html mockup from this and that site”. In every tutorial there are code parts which are used again and again, if you dont know that you have to read some more books on webdevelopment.

    This tutorial is written by me and i was sittin on it some hours so dont come and say its stolen, thats not fair.

    • Jake

      Its obvious you trolled the code, its EXACTLY the same, you just broke it up into ‘STEP’ increments and added fluff, that’s still called theft. If you submitted this article in a class, they would toss you out for plagiarism, it’s one thing referring to someone’s work and building on it, but its another trying to claim credit for it directly and changing a few letters here and there.

      Compare the dates, Derek Allard’s is written way before yours, you just happen to add a bit more code to it + SQL schema. The code is his…

      Give credit where credit is due and stop crying that people called you on your plagiarism.

  • http://www.prozorama.com yomi
  • http://www.prozorama.com yomi

    oops. sorry. troll already post it. didn’t see…

  • peterXP

    goog tuturial but not enough,
    it’s not suitable for newbie, i try to typing follow your tutorial but confuse!
    after that i copy and paste to test, it’s not work

    please fix the code!!!
    thanks!

    • http://www.newarts.at Drazen Mokic
      Author

      @peterXP

      You can`t just copy & paste the code, of course it will not work. You need to setup a database and edit the database.php and some other files.

      Try to read again, slowly and carefully. If you have specific questions i will help you.

  • http://www.incisivepoint.com Robby Radhika

    CI absolutely kick ass php framework. :) nice share.

  • http://wawaweewa.com Wawaweewa

    Nice copy-paste !

  • Ashok

    When I tried this example

    I get the message

    Severity: Warning

    Message: Cannot modify header information – headers already sent by (output started at D:\xampp\htdocs\cbe\system\application\controllers\feed.php:26)

    Filename: controllers/feed.php

    Line Number: 22

    • Daniel Vidal

      I had the same problem, try setting the header like this:
      $this->output->set_header(“Content-Type: application/rss+xml”);

  • stefan

    same for me… I get a Cannot modify header information message…

    any suggestions?

  • Bogdan

    Hi,

    I have a problem, after I create the RSS Feed Controller and View I click the “Subscribe to RSS” link but it does not open the “Choose your RSS reader” page. It shows me my RSS code.

    Can anyone, please, tell me how to fix this?

    Thanks!

  • jay

    Hi,

    I followed all the instructions ,but I get and error when I load it
    when I load it. I am totally new to Ci please help.

    Copyright

    result() as $post): ?>

    id) ?>
    id) ?>

    <!–[CDATA[

    A PHP Error was encountered

    Severity: Notice
    Message: Undefined variable: post
    Filename: views/rss.php
    Line Number: 21

    A PHP Error was encountered

    Severity: Notice
    Message: Trying to get property of non-object
    Filename: views/rss.php
    Line Number: 21

    ]]–>
    date; ?>

  • http://marshallklickman.com Marshall

    First of all, I agree with several of the above posters alleging that the code from this tutorial is ripped directly from Derek Allard’s blog, here:

    http://derekallard.com/blog/post/building-an-rss-feed-in-code-igniter/

    Not only is the code in this tutorial a character-for-character match, but the tutorial from Derek Allard actually features the *complete* code for the view file, rss.php. Which brings me to my next point.

    For those of you having problems getting this tutorial to work, it’s because the code for the view file “rss.php” is not complete. It is very obviously missing quite a lot. For instance, when he talks about referencing the $data array in the view, none of the variables from that array are even used. Also, for what it’s worth, the formatting is virtually nonexistent. Even a relative noob should be able to *sort-of* see what’s going on, which is not the case.

    If you follow the post I linked to above, you won’t have any problems. And Drazen, this was seriously not cool. Nettuts is a great resource that a lot of aspiring (and professional) developers rely on. When we come here for information, we expect it to be top-shelf (and original). When you take someone else’s work as your own, and it doesn’t even do what you say it will do, it leaves a lot of people confused and angry. I, personally, find it hard to believe this tutorial has been here over a year without anyone noticing that it is a rip-off. In the future, please think twice before abusing our trust.

    • http://mediagearhead.com Giles

      Well said good sir.

    • http://danaemc.com Danae

      Oh, my. I’m just learning CI and XML, but I know PHP and thought there was a lot missing.

      I know Nettuts is a great resource, but this article isn’t helping that at all. Can someone get Jeffrey onto this?

  • flo_core

    Why do you make me spend 30 minutes on a tutorial just to find out that it
    a) doesn’t work
    b) has incomplete code
    and
    c) is a rip-off??

    NettutsMINUS!

    • http://peewee1002.co.uk peter Sawyer

      Its been two years. Versions change…… prob one line not working now.

      • http://danaemc.com Danae

        The tutorial by Derek Allard was made four years ago and still works, with the exception of “orderby”.

  • http://amitmondal.wordpress.com amit

    Nice post….thanks
    Please visit this blog for learn more PHP scripts….

    http://amitmondal.wordpress.com/2011/01/22/gmail-rss-feed-with-unread-email-in-php/

  • Amit Deshmukh

    I am newbie to CI. I will be getting more posts from here.

  • http://techanswers.in Techie Salsan

    thank you for your advises. i am gonna implement rss feed for my classified ads website which was built on codeigniter. i will let you know once its ready..

  • http://www.goforexpert.com/ pradeep

    Nice Post Thanks a lot..

  • http://www.pabxpromo.com pabx panasonic

    thanks for u shared :)

    • Funnyguy

      Lol “pabx panasonic” gr8 name. Nyways gr8 tut.

  • http://www.moquarin.com Faycal

    An RSS example with codigniter , work 100%

  • holybyte

    i wonder if it works with version _2.1.0 of CI

  • http://www.pdvictor.com peter drinnan

    What happened to the view file in this tutorial? The other code is ok but the view code is totally whack.

  • http://www.ebali-tour.com gusmang

    Nice Tutorial . is this code work for version Code igniter 2.0 ?

  • http://pavelespinal.com Pavel E.

    This is a good tutorial, plain and simple. Congratulations.

    A couple of suggestions here:

    - Update the article’s code :)

    - Learn to ignore trolls
    Dude, you did a good job, ignore the trolls.

    - Ignore the “you don’t need CI for that” type of comments. This article is obviously for people that want to use CodeIgniter.

  • ja

    this tutorial has so mutch error ind the code

    for what do you use $this->load->helper(‘xml’); ???

    if you dont know why you loaded it take a look at the orginal tut
    http://www.derekallard.com/blog/post/building-an-rss-feed-in-code-igniter/