Advertisement
  1. Code
  2. PHP
  3. CodeIgniter

Build an RSS 2.0 Feed with CodeIgniter

Scroll to top
9 min read

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 ProductFinished ProductFinished 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.

1
    CREATE TABLE IF NOT EXISTS `posts` (
2
      `id` int(11) NOT NULL AUTO_INCREMENT,
3
      `title` varchar(120) NOT NULL,
4
      `text` text NOT NULL,
5
      `date` date NOT NULL,
6
      PRIMARY KEY (`id`)
7
    ) ENGINE=MyISAM;
8
    
9
    INSERT INTO `posts` (`id`, `title`, `text`, `date`) VALUES
10
    (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'),
11
    (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'),
12
    (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:

1
	$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:

1
	$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:

1
	$db['default']['hostname'] = "localhost"; // your host

2
    $db['default']['username'] = "root";
3
    $db['default']['password'] = "";
4
    $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:

1
	$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.

1
	class Feed extends Controller {
2
      
3
      function Feed()
4
      {
5
		parent::Controller();
6
      }
7
}

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.

1
class Feed extends Controller {
2
      
3
      function Feed()
4
      {
5
        parent::Controller();
6
        
7
        $this->load->helper('xml');
8
		$this->load->helper('text');
9
      }
10
}

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.

1
class Posts_model extends Model {
2
	
3
	// get all postings

4
	function getPosts($limit = NULL)
5
	{
6
		return $this->db->get('posts', $limit);
7
	}
8
}

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.

1
class Feed extends Controller {
2
      
3
      function Feed()
4
      {
5
        parent::Controller();
6
        
7
        $this->load->helper('xml');
8
		$this->load->helper('text');
9
        $this->load->model('posts_model', 'posts');
10
      }
11
}

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.

1
	function index()
2
	{
3
		$data['feed_name'] = 'MyWebsite.com'; // your website

4
		$data['encoding'] = 'utf-8'; // the encoding

5
        $data['feed_url'] = 'http://www.MyWebsite.com/feed'; // the url to your feed

6
        $data['page_description'] = 'What my site is about comes here'; // some description

7
        $data['page_language'] = 'en-en'; // the language

8
        $data['creator_email'] = 'mail@me.com'; // your email

9
        $data['posts'] = $this->posts->getPosts(10);  
10
        header("Content-Type: application/rss+xml"); // important!

11
	}

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.

1
	function index()
2
	{
3
		$data['feed_name'] = 'MyWebsite.com'; 
4
		$data['encoding'] = 'utf-8'; // the encoding

5
        $data['feed_url'] = 'http://www.MyWebsite.com/feed'; 
6
        $data['page_description'] = 'What my site is about comes here'; 
7
        $data['page_language'] = 'en-en'; 
8
        $data['creator_email'] = 'mail@me.com';
9
        $data['posts'] = $this->posts->getPosts(10);  
10
        header("Content-Type: application/rss+xml"); 
11
        
12
        $this->load->view('rss', $data);
13
	}

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:

1
class Feed extends Controller {
2
	
3
	function Feed()
4
	{
5
		parent::Controller();
6
		
7
		$this->load->helper('xml');
8
		$this->load->helper('text');
9
        $this->load->model('posts_model', 'posts');
10
	}
11
	
12
	function index()
13
	{
14
		$data['feed_name'] = 'MyWebsite.com';
15
		$data['encoding'] = 'utf-8';
16
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
17
        $data['page_description'] = 'What my site is about comes here';
18
        $data['page_language'] = 'en-en';
19
        $data['creator_email'] = 'mail@me.com';
20
        $data['posts'] = $this->posts->getPosts(10);    
21
        header("Content-Type: application/rss+xml");
22
		
23
		$this->load->view('rss', $data);
24
	}
25
	
26
}

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.

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

Followed by some rss meta information.

1
    <rss version="2.0"
2
        xmlns:dc="http://purl.org/dc/elements/1.1/"
3
        xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
4
        xmlns:admin="http://webns.net/mvcb/"
5
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
6
        xmlns:content="http://purl.org/rss/1.0/modules/content/">
7
    
8
        <channel>

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

1
    <title><?php echo $feed_name; ?></title>
2
3
    <link><?php echo $feed_url; ?></link>
4
    <description><?php echo $page_description; ?></description>
5
    <dc:language><?php echo $page_language; ?></dc:language>
6
    <dc:creator><?php echo $creator_email; ?></dc:creator>
7
8
    <dc:rights>Copyright <?php echo gmdate("Y", time()); ?></dc:rights>
9
    <admin:generatorAgent rdf:resource="http://www.codeigniter.com/" />

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

1
    <?php foreach($posts->result() as $post): ?>
2
    
3
       <item>
4
5
          <title><?php echo xml_convert($post->title); ?></title>
6
          <link><?php echo site_url('YOUR URL' . $post->id) ?></link>
7
          <guid><?php echo site_url('YOUR URL' . $post->id) ?></guid>
8
9
          	<description><![CDATA[ <?php echo character_limiter($post->text, 200); ?> ]]></description>
10
			<pubDate><?php echo $post->date; ?></pubDate>
11
        </item>
12
13
        
14
    <?php endforeach; ?>
15
	
16
    	</channel>
17
	<</rss>

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

1
class Feed extends Controller {
2
	
3
	function Feed()
4
	{
5
		parent::Controller();
6
		
7
		$this->load->helper('xml');
8
		$this->load->helper('text');
9
        $this->load->model('posts_model', 'posts');
10
	}
11
	
12
	function index()
13
	{
14
		$data['feed_name'] = 'MyWebsite.com';
15
		$data['encoding'] = 'utf-8';
16
        $data['feed_url'] = 'http://www.MyWebsite.com/feed';
17
        $data['page_description'] = 'What my site is about comes here';
18
        $data['page_language'] = 'en-en';
19
        $data['creator_email'] = 'mail@me.com';
20
        $data['posts'] = $this->posts->getPosts(10);    
21
        header("Content-Type: application/rss+xml");
22
		
23
		$this->load->view('rss', $data);
24
	}
25
	
26
}

system/application/models/posts_model.php

1
class Posts_model extends Model {
2
	
3
	// get all postings

4
	function getPosts($limit = NULL)
5
	{
6
		return $this->db->get('posts', $limit);
7
	}
8
}

system/application/views/rss.php

1
	<?php  echo '<?xml version="1.0" encoding="' . $encoding . '"?>' . "\n"; ?>
2
    <rss version="2.0"
3
        xmlns:dc="http://purl.org/dc/elements/1.1/"
4
        xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
5
        xmlns:admin="http://webns.net/mvcb/"
6
        xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
7
        xmlns:content="http://purl.org/rss/1.0/modules/content/">
8
    
9
        <channel>
10
        
11
        <title><?php echo $feed_name; ?></title>
12
    
13
        <link><?php echo $feed_url; ?></link>
14
        <description><?php echo $page_description; ?></description>
15
        <dc:language><?php echo $page_language; ?></dc:language>
16
        <dc:creator><?php echo $creator_email; ?></dc:creator>
17
    
18
        <dc:rights>Copyright <?php echo gmdate("Y", time()); ?></dc:rights>
19
        <admin:generatorAgent rdf:resource="http://www.codeigniter.com/" />
20
    
21
        <?php foreach($posts->result() as $post): ?>
22
        
23
            <item>
24
    
25
              <title><?php echo xml_convert($post->title); ?></title>
26
              <link><?php echo site_url('blog/posting/' . $post->id) ?></link>
27
              <guid><?php echo site_url('blog/posting/' . $post->id) ?></guid>
28
    
29
                <description><![CDATA[ <?php echo character_limiter($post->text, 200); ?> ]]></description>
30
                <pubDate><?php echo $post->date; ?></pubDate>
31
            </item>
32
    
33
            
34
        <?php endforeach; ?>
35
        
36
        </channel>
37
    </rss>

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.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.