Ketan Patel

Creating RSS Feed in CakePHP


rss feed in cakephp



In this post we will learn how to create rss feed in cakephp.This is very easy tutorial to understand and implement.We are going to use cakephp simple blog tutorial here.



Lets first setup our database for the posts.Simply run the following SQL query into your database.



CREATE TABLE `posts`(
   `id` INT NOT NULL AUTO_INCREMENT,
   `title` VARCHAR(255) NOT NULL,
   `body` TEXT NOT NULL,
   `created` DATETIME NOT NULL,
   `modified` DATETIME NOT NULL,
   PRIMARY KEY(`id`)
);

 // sample data posts for testing 


INSERT INTO `posts`(`title`,`body`, `created`, `modified`)

VALUES

 ('This is Post title One', 'Test Post body one ', NOW(), NOW()),

 ('This is Post title Two', ' Test Post body two', NOW(), NOW()),

 ('This is Post title Three', 'Test  Post body three', NOW(), NOW()),

 ('This is Post title Four', 'Test  Post body four', NOW(), NOW()),

 ('This is Post title Five', 'Test  Post body five', NOW(), NOW());

Create a Post Controller


Its time to create a controller of posts.All the business logic for posts interaction will happen in the controller. This new controller will be placed in a file called PostsController.php inside the /app/Controller directory. Simple controller looks like:


class PostController extends AppController { 
    public $helpers = array('Html', 'Form');
}

Now, lets add action to the controller. Actions represent a function in an application. For example, when you request : http://yoursite/posts/index , posts listings will be shown.code for that is:


class PostsController extends AppController { 
    public $helpers = array('Html', 'Form');

public function index() {
        $this->set('posts', $this->Post->find('all'));
    }
 }

Here note the use of set.It will pass the data that we get from the find(all) method to the view(we will create next) file.we can access the data of find(all) method using variable '$posts' in the view file.

Creating Display View for the Posts



<!-- File: /app/View/Posts/index.ctp -->



<h1>Blog posts</h1>

<table>

    <tr>

        <th>Id</th>

        <th>Title</th>
        <th>Created</th>
    </tr>

    <!-- Here is where we loop through our $posts array, printing out post info -->

    <?php foreach ($posts as $post): ?>
    <tr>
        <td><?php echo $post['Post']['id']; ?></td>
        <td>
            <?php echo $this->Html->link($post['Post']['title'],
array('controller' => 'posts', 'action' => 'view', $post['Post']['id'])); ?>
        </td>
        <td><?php echo $post['Post']['created']; ?></td>
    </tr>
    <?php endforeach; ?>
    <?php unset($post); ?>
</table>

Now go to  http://yoursite/posts/index  or  http://yoursite/posts  and you can see the list of the posts.

The real picture starts now,

(1) Go to your app/Config/routes.php file and simply add, 

Router::parseExtensions('rss');

The method Router::parseExtensions() accepts any number of extensions.Using extensions, we can create different versions of the same view. 


(2) Open your PostsController.php file and add the following component 

public $components = array('RequestHandler');

(3) Now made some changes in the index function of the Post Controller.


public function index() {
  $options = array();
  if ($this->RequestHandler->isRss()) {
    $options = array_merge($options, array(
       'order' => array('Post.created' => 'desc'),
       'limit' => 5
    ));
  }
  $posts = $this->Post->find('all', $options);
  $this->set(compact('posts'));
}

(4) Now create a new folder named "rss" in app/Views/Posts folder and create a file called index.ctp with the following contents in that folder.

 <?php
$this->set('channel', array(

   'title' => 'Recent posts',

   'link' => $this->Rss->url('/', true),

   'description' => 'New posts on my blog'

));



$items = array();
foreach($posts as $post) {
 $items[] = array(
   'title' => $post['Post']['title'],
   'link' => array('action'=>'view', $post['Post']['id']),
    'description' => array('cdata'=>true, 'value'=>$post['Post']
['body']),
    'pubDate' => $post['Post']['created']
 );
}

echo $this->Rss->items($items);
?>


(5) Create a link in posts listing page.Edit index.ctp file in app/Views/Posts folder.Add the following line in it.

<?php echo $this->Html->link('Feed', array('action'=>'index',
'ext'=>'rss')); ?>


Now browse to http://yoursite/posts, you will see a listing of posts with a link titled Feed.

ketan patel

About Ketan Patel -

I have developed a wide range of websites using CorePHP, Opencart, CakePHP and CodeIgniter including sites for startup companies and small businesses. Apart from my blogging life, I like to read Novels, Listening music and Net surfing.

Subscribe to this Blog via Email :