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
function index() { #Getting data from Database with Active Record $this->db->order_by('date', 'desc'); #order so newest posts would be first $this->db->limit(25); #25 is a great number for RSS feeds 10-20 is too few $query = $this->db->get('posts'); #make the query #RSS data $data['title'] = 'Latest Posts'; #RSS feed title $data['link'] = base_url(); #site link where the newest posts are, base_url() needs url helper $data['description'] = 'Latest posts of our site.'; #describe the feeds $data['items'] = $query->result(); #put posts to our $data array $this->_rss2($data); #generate RSS code }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
function _rss2($data) { echo '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">', '<channel>', '<title>',$data['title'],'</title>', '<link>',$data['link'],'</link>', '<description>',$data['description'],'</description>', '<atom:link href="',base_url(),'rss" rel="self" type="application/rss+xml" />'; foreach($data['items'] as $item) echo '<item>', '<title>',xml_convert($item->title),'</title>', '<link>',base_url(),'post/',$item->url_title,'</link>', '<description>',xml_convert($item->description),'</description>', '<guid>',base_url(),'post/',$item->url_title,'</guid>', '</item>'; echo '</channel>', '</rss>'; }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.