22 August 2010

In this tutorial we will make RSS 2.0 feeds from latest posts in your site.

Getting started:

I made rss named controller, so I would access my feeds at address that looks like: "example.com/rss". If you want to know more about RSS 2.0 then you should read RSS 2.0 Specification. In our controller we need to load two libraries: xml helper and database library for Active Record. Now we should have nice setup and lets get ready to fill our index function with code.

index Function:

We put all the data to on array and then catch them in other function. If you don't have anything in your database then you can type yo posts manually as well.
Source code viewer
  1. function index() {
  2. #Getting data from Database with Active Record
  3. $this->db->order_by('date', 'desc'); #order so newest posts would be first
  4. $this->db->limit(25); #25 is a great number for RSS feeds 10-20 is too few
  5. $query = $this->db->get('posts'); #make the query
  6. #RSS data
  7. $data['title'] = 'Latest Posts'; #RSS feed title
  8. $data['link'] = base_url(); #site link where the newest posts are, base_url() needs url helper
  9. $data['description'] = 'Latest posts of our site.'; #describe the feeds
  10.  
  11. $data['items'] = $query->result(); #put posts to our $data array
  12.  
  13. $this->_rss2($data); #generate RSS code
  14. }
Programming Language: PHP

_rss2 Function:

We use underscore before function name so it would not be accessible later from your site, by url. Then set the header to xml file. And echo the results. You probably have to change item values, because you might have different data at database. I don't think that it's necessary to use views and models here. It would only make more mess. We use CodeIgniters xml helper to clear our values from forbidden characters.
Source code viewer
  1. function _rss2($data) {
  2. header('Content-type: text/xml');
  3. echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">',
  4. '<channel>',
  5. '<title>',$data['title'],'</title>',
  6. '<link>',$data['link'],'</link>',
  7. '<description>',$data['description'],'</description>',
  8. '<atom:link href="',base_url(),'rss" rel="self" type="application/rss+xml" />';
  9. foreach($data['items'] as $item) echo
  10. '<item>',
  11. '<title>',xml_convert($item->title),'</title>',
  12. '<link>',base_url(),'post/',$item->url_title,'</link>',
  13. '<description>',xml_convert($item->description),'</description>',
  14. '<pubDate>',date(DATE_RSS, strtotime($item->date)),'</pubDate>',
  15. '<guid>',base_url(),'post/',$item->url_title,'</guid>',
  16. '</item>';
  17. echo '</channel>',
  18. '</rss>';
  19. }
Programming Language: PHP
If you have any questions about the rss code then please read the RSS 2.0 Specification. And when the feeds are dome you can use RSS Validator to validate the feeds.