Yii2 框架扩展,使用 zend-feed 库提供消费 RSS 和 Atom 资源的功能。

安装次数: 18

依赖项: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 1

公开问题: 0

类型:yii2-extension

dev-master 2016-12-05 03:56 UTC

This package is not auto-updated.

Last update: 2024-09-23 14:13:28 UTC


README

Yii2 框架扩展,使用 zend-feed 库提供消费 RSS 和 Atom 资源的功能。

安装

php composer.phar require "shuguang/yii2-rss:dev-master"

{
	"require": 
	{
  		"shuguang/yii2-rss": "dev-master"
	}
}

配置

在配置文件中

/config/web.php

添加资源组件

'components' => array(
	...
	'feed' => array(
		'class' => 'yii\feed\FeedDriver',
	),
)

简单用法

读取 RSS 资源

$feed=Yii::$app->feed->reader()->import('http://exapmple.com/feed.rss');

这将获取 RSS 资源,解析它并返回资源对象。更多详细信息,您可以阅读官方 Zend-feed 扩展文档:http://framework.zend.com/manual/2.2/en/modules/zend.feed.reader.html

创建 RSS 资源

在控制器中创建 Rss 动作

public function actionRss(){
		
    $feed=Yii::$app->feed->writer();
    $feed->setTitle(Yii::$app->params['title']);
	$feed->setLink('http://example.com');
	$feed->setFeedLink('http://example.com/rss', 'rss');
	$feed->setDescription(Yii::t('app','Recent headlines'));
	$feed->setGenerator('http://example.com/rss');
	$feed->setDateModified(time()); 
	/**
	* Add one or more entries. Note that entries must
	* be manually added once created.
	*/
	$posts=Post::find()->orderBy('id DESC')->limit(20)->all();
	foreach($posts as $post){
			$entry = $feed->createEntry();
			$entry->setTitle($post->title);
			$entry->setLink(Yii::$app->urlManager->createAbsoluteUrl('/post/view',['id'=>$post->id]));
			$entry->setDateModified(intval($post->created));
			$entry->setDateCreated(intval($post->created));
			$entry->setContent(
			   $post->content
			);
			$entry->setEnclosure(
				[
				 'uri'=>$post->image,
				 'type'=>'image/jpeg',
				 'length'=>filesize(Yii::getAlias('@webroot').$post->image)
				 ]
			);
			$feed->addEntry($entry);
	}
	/**
	* Render the resulting feed to Atom 1.0 and assign to $out.
	* You can substitute "atom" with "rss" to generate an RSS 2.0 feed.
	*/
	$out = $feed->export('rss');
	header('Content-type: text/xml');
	echo $out;
	die();
}

然后最好使用缓存组件进行缓存

public function behaviors() {
	return [
		....
		'cache'=> [
			'only'=>['rss'],
			'class'=>PageCache::className(),
			'duration'=>0,
			'dependency'=>[
				'class' => 'yii\caching\DbDependency',
				'sql' => 'SELECT max(time_updated) as max FROM tbl_post',
			],
		]
	];
}

有关 Zend-feed 的更多高级用法,请参阅官方文档:http://framework.zend.com/manual/2.2/en/modules/zend.feed.writer.html