How to generate Web feed for an application

You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.

« previous (#2)next (#5) »

Web feed is a data format used for providing users with frequently updated content. In this article, we describe how to use Zend_Feed, an excellent component from Zend Framework to generate Web feed for an Yii application. This article can also serve as a general guide on how to use other components in Zend Framework.

To begin with, we download Zend Framework and extract it to the directory protected/vendors/Zend. Verify the file protected/vendors/Zend/Feed.php exists.

Then, in SiteController (or another controller if you like) create a feed action as follows,

Yii::import('application.vendors.*');
require_once('Zend/Feed.php');

public function actionFeed()
{
	// retrieve the latest 20 posts
	$posts=Post::model()->findAll(array(
		'order'=>'createTime DESC',
		'limit'=>20,
	));
	// convert to the format needed by Zend_Feed
	$entries=array();
	foreach($posts as $post)
	{
		$entries[]=array(
			'title'=>$post->title,
			'link'=>$this->createUrl('post/show',array('id'=>$post->id)),
			'description'=>$post->content,
			'lastUpdate'=>$post->createTime,
		);
	}
	// generate and render RSS feed
	$feed=Zend_Feed::importArray(array(
		'title'   => 'My Post Feed',
		'link'    => $this->createUrl(''),
		'charset' => 'UTF-8',
		'entries' => $entries,		
	), 'rss');
	$feed->send();	
}

To this end, the feed is done and we can access it via the following URL:

http://www.example.com/index.php?r=site/feed

Using the URL management feature of Yii, we can beautify the above URL to something like http://www.example.com/feed.xml.

We can insert this link to the head section of a page using the following code:

Yii::app()->clientScript->registerLinkTag(
	'alternate',
	'application/rss+xml',
	$this->createUrl('site/feed'));

We can also use [CHtml::linkTag()] to directly insert the link tag at the current place in a page. The difference between these approaches is that the former code can be written anywhere while the latter can only appear in the head section of a view (or layout).

The Zend_Feed component has many other features. If you are interested, please refer to its documentation.

Links

Chinese version

3 0
9 followers
Viewed: 37 324 times
Version: Unknown (update)
Category: Tutorials
Tags:
Written by: qiang
Last updated by: Yang He
Created on: Feb 28, 2009
Last updated: 11 years ago
Update Article

Revisions

View all history