使用了Yii的efeed扩展(地址:http://www.yiiframework.com/extension/efeed/)
把文档中的代码修改下放入view:
<?php Yii::import('ext.feed.*'); $feed = new EFeed(EFeed::ATOM); $title=$catalog?Yii::app()->name.' - '.$catalog->Label:Yii::app()->name; $feed->title = $title; $link=$catalog?'http://yiiblog.net'.' - '.CHtml::normalizeUrl($catalog->Link):'http://yiiblog.net'; $feed->link =$link; $feed->addChannelTag('updated', date(DATE_ATOM, time())); $feed->addChannelTag('author', array('name'=>'Yii')); foreach ($models as $model) { $item = $feed->createNewItem(); $item->title = $model->title; $item->link = 'http://yiiblog.net'.CHtml::normalizeUrl($model->Link); $item->date=$model->created_time; $item->description=$model->content; $feed->addItem($item); } $feed->generateFeed(); ?>
然后修改model,加入一个feed的namescope:
public function feed($catalog=false){ $option=array( 'order'=>'t.id DESC', 'limit'=>10, ); if ($catalog!=false) { $option['condition']='catalog=:catalog'; $option['params']=array(':catalog'=>$catalog); $option['limit']=3; } $this->getDbCriteria()->mergeWith($option); return $this; }
再加入controller,这个很轻:
public function actionFeed($catalog=false) { // renders the view file 'protected/views/site/index.php' // using the default layout 'protected/views/layouts/main.php' $catalogmodel=$catalog?$this->loadCatalog($catalog):false; $this->renderPartial('rss',array( 'models'=>Post::model()->feed($catalog)->findAll(), 'catalog'=>$catalogmodel, )); Yii::app()->end(); }
再在urlmanager里加入记录,方便访问:
'feed'=>'site/feed', 'feed/<catalog:\d+>'=>'site/feed',
然后就完工了。
现在可以通过http://yiiblog.net/feed来取得全站的rss(atom),也可以通过http://yiiblog.net/feed/数字id的方式来取得分类下的文章的rss(atom)。