PHP自訂RSS文件
這篇要介紹用PHP產生自訂RSS頁面的方法,關於RSS原理可以參考Wiki :http://zh.wikipedia.org/wiki/RSS
簡略的來說,RSS (Really Simple Syndication) 是一種用來分發和匯集網頁內容的 XML 格式,訂閱 RSS 後,只要透過 RSS 閱讀器,就可看到即時更新的內容,今天就是要分享如何產生一個RSS文件供使用者閱讀。
首先必須瞭解RSS 的XML格式主要架構為何,主要的標籤為<item><title><link><description>,這是產生一列的主要tag,其他的元素與架構範本可以參考此連結 : http://www.xml.com/pub/a/2002/12/18/dive-into-xml.html
接著我們只要利用資料庫來源去產生這份XML格式的文件,我們的RSS就大功告成了!程式碼如下 :
<?php
$query = "select * from `news` ";
$result = mysql_query($query);
while ($line = mysql_fetch_assoc($result))
{
$return[] = $line;
}
$now = date("D, d M Y H:i:s T"); //現在時間
$output = "<?xml version=\"1.0\"?> //XML檔頭開始
<rss version=\"2.0\">
<channel> // 以下XML基本設定
<title>My RSS</title>
<link>http://www.123.com/rss.php</link>
<description>This is My RSS~~</description>
<language>zh-tw</language>
<pubDate>$now</pubDate>
<lastBuildDate>$now</lastBuildDate>
<docs>http://www.123.com</docs>
<managingEditor>shinyo.her@gmail.com</managingEditor>
<webMaster>shinyo.her@gmail.com</webMaster>
";
//XML設定結束
foreach ($return as $line) //迴圈列出所需資料庫內容
{
$output .= "<item><title>".htmlentities($line['subject'])."</title> //標題
<link>show.php?num=".$line['num']."</link> //連結
<description>".htmlentities(strip_tags($line['word']))."</description> //簡述
</item>";
}
$output .= "</channel></rss>"; //XML結束
echo $output; //輸出執行結果!!
?>
打完收工!提醒各位該頁不需任何HTML畫面即可產生定型化的RSS瀏覽介面,可別加入其他標籤阿~~!!
|