Kohana 3: create RSS feed image

Kohana 3: create RSS feed

 

How to create a simple RSS feed with the Kohana framework (3+) through Feed class and her Create method.

The two parameters required to call Feed::Create(), are:

$info : array containing information about the feed.

$items : array with the elements/entries that will be served by the feed.

The contents of the parameters:

$info = array(
    'title' => 'Feed title',
    'pubDate' => date("D, d M Y H:i:s T"),
    'description' => 'Feed description',
    'link' => 'URL page for the feed',
    'language' => 'en-us',
);

Feed info only requires "title", "link" and "description". There are more optional elements: Optional channel elements.

$items[] = array(
    'title' => 'Title of the item',
    'link' => 'Url of the item',
    'description' => 'Item description/content',
);

Equally, further information can be added to each element: Elements of <item>.

Finally, would call the create() method, which would return the valid XML (default encoding is UTF-8).

Feed::create($info, $items)

Only remains to implement it. For example, creating an action within the controller that serve the blog entries:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public function action_rss()
{
    $this->auto_render = FALSE;
    $info = array(
        'title' => 'My blog feed',
        'description' => 'My blog description',
        'link' => 'http://example.com/blog',
    );
    $items = array();
    $posts = ORM::factory('posts')->find_all();
    foreach($posts as $post)
    {
        $items[] = array(
            'title' => $post->title,
            'link' => URL::site('blog/post/'.$post->id.'/'.URL::title($post->title, '-', TRUE)),
            'description' => $post->content,
        );
    }
    $this->response->headers('Content-Type', 'text/xml');
    $this->response->body(Feed::create($info, $items));
}

When using Kohana 3.0, replace lines 19 and 20 by the following:

$this->request->headers['Content-Type'] = 'text/xml';
$this->request->response = Feed::create($info, $items);

 

comments powered by Disqus