所以我又做了一些修改,確認每個瀏覽器打開都會認得它是一份 RSS 文件,Google Reader 也能正確讀取。
設計 RSS 功能需要用到 Controller、Model 和 View。首先是 model 的部份,這邊寫得比較簡化,要注意的是時間的部份,多做了一個 UNIX timestamp,因為 RSS 的時間格式要照 RFC #822 規範,有 timestamp 比較好轉。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class File_model extends CI_Model{
public function __construct(){
parent::__construct();
$this->load->database();
}
public function get_files(){
// 用 MySQL 內建的 UNIX_TIMESTAMP 函式取得 unix timestamp
$this->db->select("*, UNIX_TIMESTAMP(publish_date) as unixtime", FALSE);
$this->db->order_by('publish_date', 'desc');
return $this->db->get_where(TBL_NAME)->result_array();
}
}
/* End of file file_model.php */
再來是 Controller 的部份,將 Model 傳回的資料打包,準備傳給 View。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Feed extends CI_Controller {
public function __construct(){
parent::__construct();
$this->load->model('file_model', 'file');
$this->load->helper('xml');
}
public function index()
{
$data['feed_name'] = 'Qoding.us'; // your website
$data['encoding'] = 'utf-8'; // the encoding
$data['feed_url'] = base_url('feed'); // the url to your feed
$data['page_description'] = 'We love programming!'; // some description
$data['page_language'] = 'zh-tw'; // the language
$data['posts'] = $this->file->get_files();
header("Content-Type: text/xml"); // important!
$this->load->view('rss', $data);
}
}
/* End of file feed.php */
/* Location: ./application/controllers/feed.php */
最後的 View 就是 RSS XML 本身。
<?php echo '<?xml version="1.0" encoding="utf-8"?>' . "\n";?>
<rss version="2.0"
xmlns:content="http://purl.org/rss/1.0/modules/content/"
xmlns:wfw="http://wellformedweb.org/CommentAPI/"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:atom="http://www.w3.org/2005/Atom"
xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
>
<channel>
<title><?php echo $feed_name; ?></title>
<atom:link href="<?php echo $feed_url; ?>" rel="self" type="application/rss+xml" />
<link><?php echo $feed_url; ?></link>
<description><?php echo $page_description; ?></description>
<language><?php echo $page_language; ?></language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<generator>http://codeigniter.com</generator>
<?php foreach($posts as $k => $uf): ?>
<item>
<title><?php echo '篇名';?></title>
<link><?php echo 'http://本文連結';?></link>
<guid><?php echo '可以辨識本文的獨特 id,一般用 permalink 就可以';?></guid>
<description><![CDATA[
文章內容
]]></description>
<pubDate><?php echo date('r', $uf['unixtime']);?></pubDate>
</item>
<?php endforeach; ?>
</channel>
</rss>
最後產出的結果就是 http://你的網址/feed,把這網址丟到幾個瀏覽器試試,如果可以正確辨識訂閱資訊就是成功了。

Leave a Reply Cancel reply