欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php生成RSS订阅的方法

程序员文章站 2022-08-29 10:07:19
本文实例讲述了php生成rss订阅的方法。分享给大家供大家参考。具体分析如下: rss(简易信息聚合,也叫聚合内容)是一种描述和同步网站内容的格式。rss可以是以下三个解...

本文实例讲述了php生成rss订阅的方法。分享给大家供大家参考。具体分析如下:

rss(简易信息聚合,也叫聚合内容)是一种描述和同步网站内容的格式。rss可以是以下三个解释的其中一个: really simple syndication;rdf (resource description framework) site summary; rich site summary。但其实这三个解释都是指同一种syndication的技术。rss目前广泛用于网上新闻频道,blog和wiki。使用rss订阅能更快地获取信息,网站提供rss输出,有利于让用户获取网站内容的最新更新。网络用户可以在客户端借助于支持rss的聚合工具软件,在不打开网站内容页面的情况下阅读支持rss输出的网站内容。
从技术上来说一个rss文件就是一段规范的xml数据,该文件一般以rss,xml或者rdf作为后缀,下面是一段 rss 文件的内容示例:

复制代码 代码如下:
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title></title>
<link>//www.jb51.net/</link>
<description></description>
<item>
<title>rss tutorial</title>
<link>网站地址/rss</link>
<description>new rss tutorial on w3school</description>
</item>
<item>
<title>xml tutorial</title>
<link>网站地址/xml</link>
<description>new xml tutorial on w3school</description>
</item>
</channel>
</rss>

下面分享一段使用 php 动态生成 rss 的代码示例:

复制代码 代码如下:
<?php
/**
** php 动态生成 rss 类
**/
define("time_zone","");
define("feedcreator_version","www.jb51.net");//您的网址
class feeditem extends htmldescribable{
    var $title,$description,$link;
    var $author,$authoremail,$image,$category,$comments,$guid,$source,$creator;
    var $date;
    var $additionalelements=array();
}
 
class feedimage extends htmldescribable{
    var $title,$url,$link;
    var $width,$height,$description;
}
 
class htmldescribable{
    var $descriptionhtmlsyndicated;
    var $descriptiontruncsize;
 
    function getdescription(){
        $descriptionfield=new feedhtmlfield($this->description);
        $descriptionfield->syndicatehtml=$this->descriptionhtmlsyndicated;
        $descriptionfield->truncsize=$this->descriptiontruncsize;
        return $descriptionfield->output();
    }
}
 
class feedhtmlfield{
    var $rawfieldcontent;
    var $truncsize,$syndicatehtml;
    function feedhtmlfield($parfieldcontent){
        if($parfieldcontent){
            $this->rawfieldcontent=$parfieldcontent;
        }
    }
    function output(){
        if(!$this->rawfieldcontent){
            $result="";
        }    elseif($this->syndicatehtml){
            $result="<![cdata[".$this->rawfieldcontent."]]>";
        }else{
            if($this->truncsize and is_int($this->truncsize)){
                $result=feedcreator::itrunc(htmlspecialchars($this->rawfieldcontent),$this->truncsize);
            }else{
                $result=htmlspecialchars($this->rawfieldcontent);
            }
        }
        return $result;
    }
}
 
class universalfeedcreator extends feedcreator{
    var $_feed;
    function _setformat($format){
        switch (strtoupper($format)){
            case "2.0":
                // fall through
            case "rss2.0":
                $this->_feed=new rsscreator20();
                break;
            case "0.91":
                // fall through
            case "rss0.91":
                $this->_feed=new rsscreator091();
                break;
            default:
                $this->_feed=new rsscreator091();
                break;
        }
        $vars=get_object_vars($this);
        foreach ($vars as $key => $value){
            // prevent overwriting of properties "contenttype","encoding"; do not copy "_feed" itself
            if(!in_array($key, array("_feed","contenttype","encoding"))){
                $this->_feed->{$key}=$this->{$key};
            }
        }
    }
 
    function createfeed($format="rss0.91"){
        $this->_setformat($format);
        return $this->_feed->createfeed();
    }
 
    function savefeed($format="rss0.91",$filename="",$displaycontents=true){
        $this->_setformat($format);
        $this->_feed->savefeed($filename,$displaycontents);
    }
 
    function usecached($format="rss0.91",$filename="",$timeout=3600){
        $this->_setformat($format);
        $this->_feed->usecached($filename,$timeout);
    }
}
 
class feedcreator extends htmldescribable{
    var $title,$description,$link;
    var $syndicationurl,$image,$language,$copyright,$pubdate,$lastbuilddate,$editor,$editoremail,$webmaster,$category,$docs,$ttl,$rating,$skiphours,$skipdays;
    var $xslstylesheet="";
    var $items=array();
    var $contenttype="application/xml";
    var $encoding="utf-8";
    var $additionalelements=array();
 
    function additem($item){
        $this->items[]=$item;
    }
 
    function clearitem2null(){
        $this->items=array();
    }
 
    function itrunc($string,$length){
        if(strlen($string)<=$length){
            return $string;
        }
 
        $pos=strrpos($string,".");
        if($pos>=$length-4){
            $string=substr($string,0,$length-4);
            $pos=strrpos($string,".");
        }
        if($pos>=$length*0.4){
            return substr($string,0,$pos+1)." ...";
        }
 
        $pos=strrpos($string," ");
        if($pos>=$length-4){
            $string=substr($string,0,$length-4);
            $pos=strrpos($string," ");
        }
        if($pos>=$length*0.4){
            return substr($string,0,$pos)." ...";
        }
 
        return substr($string,0,$length-4)." ...";
    }
 
    function _creategeneratorcomment(){
        return "<!-- generator=\"".feedcreator_version."\" -->\n";
    }
 
    function _createadditionalelements($elements,$indentstring=""){
        $ae="";
        if(is_array($elements)){
            foreach($elements as $key => $value){
                $ae.= $indentstring."<$key>$value</$key>\n";
            }
        }
        return $ae;
    }
 
    function _createstylesheetreferences(){
        $xml="";
        if($this->cssstylesheet) $xml .= "<?xml-stylesheet href=\"".$this->cssstylesheet."\" type=\"text/css\"?>\n";
        if($this->xslstylesheet) $xml .= "<?xml-stylesheet href=\"".$this->xslstylesheet."\" type=\"text/xsl\"?>\n";
        return $xml;
    }
 
    function createfeed(){}
 
    function _generatefilename(){
        $fileinfo=pathinfo($_server["php_self"]);
        return substr($fileinfo["basename"],0,-(strlen($fileinfo["extension"])+1)).".xml";
    }
 
    function _redirect($filename){
        header("content-type: ".$this->contenttype."; charset=".$this->encoding."; filename=".basename($filename));
        header("content-disposition: inline; filename=".basename($filename));
        readfile($filename,"r");
        die();
    }
 
    function usecached($filename="",$timeout=3600){
        $this->_timeout=$timeout;
        if($filename==""){
            $filename=$this->_generatefilename();
        }
        if(file_exists($filename) && (time()-filemtime($filename) < $timeout)){
            $this->_redirect($filename);
        }
    }
 
    function savefeed($filename="",$displaycontents=true){
        if($filename==""){
            $filename=$this->_generatefilename();
        }
        $feedfile=fopen($filename,"w+");
        if($feedfile){
            fputs($feedfile,$this->createfeed());
            fclose($feedfile);
            if($displaycontents){
                $this->_redirect($filename);
            }
        }else{
            echo "<br /><b>error creating feed file, please check write permissions.</b><br />";
        }
    }
}
 
class feeddate{
    var $unix;
    function feeddate($datestring=""){
        if($datestring=="") $datestring=date("r");
        if(is_integer($datestring)){
            $this->unix=$datestring;
            return;
        }
        if(preg_match("~(?:(?:mon|tue|wed|thu|fri|sat|sun),\\s+)?(\\d{1,2})\\s+([a-za-z]{3})\\s+(\\d{4})\\s+(\\d{2}):(\\d{2}):(\\d{2})\\s+(.*)~",$datestring,$matches)){
            $months=array("jan"=>1,"feb"=>2,"mar"=>3,"apr"=>4,"may"=>5,"jun"=>6,"jul"=>7,"aug"=>8,"sep"=>9,"oct"=>10,"nov"=>11,"dec"=>12);
            $this->unix=mktime($matches[4],$matches[5],$matches[6],$months[$matches[2]],$matches[1],$matches[3]);
            if(substr($matches[7],0,1)=='+' or substr($matches[7],0,1)=='-'){
                $tzoffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60;
            }else{
                if(strlen($matches[7])==1){
                    $onehour=3600;
                    $ord=ord($matches[7]);
                    if($ord < ord("m")){
                        $tzoffset=(ord("a") - $ord - 1) * $onehour;
                    } elseif($ord >= ord("m") && $matches[7]!="z"){
                        $tzoffset=($ord - ord("m")) * $onehour;
                    } elseif($matches[7]=="z"){
                        $tzoffset=0;
                    }
                }
                switch ($matches[7]){
                    case "ut":
                    case "gmt":    $tzoffset=0;
                }
            }
            $this->unix += $tzoffset;
            return;
        }
        if(preg_match("~(\\d{4})-(\\d{2})-(\\d{2})t(\\d{2}):(\\d{2}):(\\d{2})(.*)~",$datestring,$matches)){
            $this->unix=mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]);
            if(substr($matches[7],0,1)=='+' or substr($matches[7],0,1)=='-'){
                $tzoffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60;
            }else{
                if($matches[7]=="z"){
                    $tzoffset=0;
                }
            }
            $this->unix += $tzoffset;
            return;
        }
        $this->unix=0;
    }
 
    function rfc822(){
        $date=gmdate("y-m-d h:i:s",$this->unix);
        if(time_zone!="") $date .= " ".str_replace(":","",time_zone);
        return $date;
    }
 
    function iso8601(){
        $date=gmdate("y-m-d h:i:s",$this->unix);
        $date=substr($date,0,22) . ':' . substr($date,-2);
        if(time_zone!="") $date=str_replace("+00:00",time_zone,$date);
        return $date;
    }
 
    function unix(){
        return $this->unix;
    }
}
 
class rsscreator10 extends feedcreator{
    function createfeed(){
        $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n";
        $feed.= $this->_creategeneratorcomment();
        if($this->cssstylesheet==""){
            $cssstylesheet="http://www.w3.org/2000/08/w3c-synd/style.css";
        }
        $feed.= $this->_createstylesheetreferences();
        $feed.= "<rdf:rdf\n";
        $feed.= "    xmlns=\"http://purl.org/rss/1.0/\"\n";
        $feed.= "    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n";
        $feed.= "    xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n";
        $feed.= "    xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n";
        $feed.= "    <channel rdf:about=\"".$this->syndicationurl."\">\n";
        $feed.= "        <title>".htmlspecialchars($this->title)."</title>\n";
        $feed.= "        <description>".htmlspecialchars($this->description)."</description>\n";
        $feed.= "        <link>".$this->link."</link>\n";
        if($this->image!=null){
            $feed.= "        <image rdf:resource=\"".$this->image->url."\" />\n";
        }
        $now=new feeddate();
        $feed.= "       <dc:date>".htmlspecialchars($now->iso8601())."</dc:date>\n";
        $feed.= "        <items>\n";
        $feed.= "            <rdf:seq>\n";
        for ($i=0;$i<count($this->items);$i++){
            $feed.= "                <rdf:li rdf:resource=\"".htmlspecialchars($this->items[$i]->link)."\"/>\n";
        }
        $feed.= "            </rdf:seq>\n";
        $feed.= "        </items>\n";
        $feed.= "    </channel>\n";
        if($this->image!=null){
            $feed.= "    <image rdf:about=\"".$this->image->url."\">\n";
            $feed.= "        <title>".$this->image->title."</title>\n";
            $feed.= "        <link>".$this->image->link."</link>\n";
            $feed.= "        <url>".$this->image->url."</url>\n";
            $feed.= "    </image>\n";
        }
        $feed.= $this->_createadditionalelements($this->additionalelements,"    ");
 
        for ($i=0;$i<count($this->items);$i++){
            $feed.= "    <item rdf:about=\"".htmlspecialchars($this->items[$i]->link)."\">\n";
            //$feed.= "        <dc:type>posting</dc:type>\n";
            $feed.= "        <dc:format>text/html</dc:format>\n";
            if($this->items[$i]->date!=null){
                $itemdate=new feeddate($this->items[$i]->date);
                $feed.= "        <dc:date>".htmlspecialchars($itemdate->iso8601())."</dc:date>\n";
            }
            if($this->items[$i]->source!=""){
                $feed.= "        <dc:source>".htmlspecialchars($this->items[$i]->source)."</dc:source>\n";
            }
            if($this->items[$i]->author!=""){
                $feed.= "        <dc:creator>".htmlspecialchars($this->items[$i]->author)."</dc:creator>\n";
            }
            $feed.= "        <title>".htmlspecialchars(strip_tags(strtr($this->items[$i]->title,"\n\r","  ")))."</title>\n";
            $feed.= "        <link>".htmlspecialchars($this->items[$i]->link)."</link>\n";
            $feed.= "        <description>".htmlspecialchars($this->items[$i]->description)."</description>\n";
            $feed.= $this->_createadditionalelements($this->items[$i]->additionalelements,"        ");
            $feed.= "    </item>\n";
        }
        $feed.= "</rdf:rdf>\n";
        return $feed;
    }
}
 
class rsscreator091 extends feedcreator{
    var $rssversion;
 
    function rsscreator091(){
        $this->_setrssversion("0.91");
        $this->contenttype="application/rss+xml";
    }
 
    function _setrssversion($version){
        $this->rssversion=$version;
    }
 
    function createfeed(){
        $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n";
        $feed.= $this->_creategeneratorcomment();
        $feed.= $this->_createstylesheetreferences();
        $feed.= "<rss version=\"".$this->rssversion."\">\n";
        $feed.= "    <channel>\n";
        $feed.= "        <title>".feedcreator::itrunc(htmlspecialchars($this->title),100)."</title>\n";
        $this->descriptiontruncsize=500;
        $feed.= "        <description>".$this->getdescription()."</description>\n";
        $feed.= "        <link>".$this->link."</link>\n";
        $now=new feeddate();
        $feed.= "        <lastbuilddate>".htmlspecialchars($now->rfc822())."</lastbuilddate>\n";
        $feed.= "        <generator>".feedcreator_version."</generator>\n";
 
        if($this->image!=null){
            $feed.= "        <image>\n";
            $feed.= "            <url>".$this->image->url."</url>\n";
            $feed.= "            <title>".feedcreator::itrunc(htmlspecialchars($this->image->title),100)."</title>\n";
            $feed.= "            <link>".$this->image->link."</link>\n";
            if($this->image->width!=""){
                $feed.= "            <width>".$this->image->width."</width>\n";
            }
            if($this->image->height!=""){
                $feed.= "            <height>".$this->image->height."</height>\n";
            }
            if($this->image->description!=""){
                $feed.= "            <description>".$this->image->getdescription()."</description>\n";
            }
            $feed.= "        </image>\n";
        }
        if($this->language!=""){
            $feed.= "        <language>".$this->language."</language>\n";
        }
        if($this->copyright!=""){
            $feed.= "        <copyright>".feedcreator::itrunc(htmlspecialchars($this->copyright),100)."</copyright>\n";
        }
        if($this->editor!=""){
            $feed.= "        <managingeditor>".feedcreator::itrunc(htmlspecialchars($this->editor),100)."</managingeditor>\n";
        }
        if($this->webmaster!=""){
            $feed.= "        <webmaster>".feedcreator::itrunc(htmlspecialchars($this->webmaster),100)."</webmaster>\n";
        }
        if($this->pubdate!=""){
            $pubdate=new feeddate($this->pubdate);
            $feed.= "        <pubdate>".htmlspecialchars($pubdate->rfc822())."</pubdate>\n";
        }
        if($this->category!=""){
            $feed.= "        <category>".htmlspecialchars($this->category)."</category>\n";
        }
        if($this->docs!=""){
            $feed.= "        <docs>".feedcreator::itrunc(htmlspecialchars($this->docs),500)."</docs>\n";
        }
        if($this->ttl!=""){
            $feed.= "        <ttl>".htmlspecialchars($this->ttl)."</ttl>\n";
        }
        if($this->rating!=""){
            $feed.= "        <rating>".feedcreator::itrunc(htmlspecialchars($this->rating),500)."</rating>\n";
        }
        if($this->skiphours!=""){
            $feed.= "        <skiphours>".htmlspecialchars($this->skiphours)."</skiphours>\n";
        }
        if($this->skipdays!=""){
            $feed.= "        <skipdays>".htmlspecialchars($this->skipdays)."</skipdays>\n";
        }
        $feed.= $this->_createadditionalelements($this->additionalelements,"    ");
 
        for ($i=0;$i<count($this->items);$i++){
            $feed.= "        <item>\n";
            $feed.= "            <title>".feedcreator::itrunc(htmlspecialchars(strip_tags($this->items[$i]->title)),100)."</title>\n";
            $feed.= "            <link>".htmlspecialchars($this->items[$i]->link)."</link>\n";
            $feed.= "            <description>".$this->items[$i]->getdescription()."</description>\n";
 
            if($this->items[$i]->author!=""){
                $feed.= "            <author>".htmlspecialchars($this->items[$i]->author)."</author>\n";
            }
            /*
             // on hold
             if($this->items[$i]->source!=""){
             $feed.= "            <source>".htmlspecialchars($this->items[$i]->source)."</source>\n";
             }
             */
            if($this->items[$i]->category!=""){
                $feed.= "            <category>".htmlspecialchars($this->items[$i]->category)."</category>\n";
            }
            if($this->items[$i]->comments!=""){
                $feed.= "            <comments>".htmlspecialchars($this->items[$i]->comments)."</comments>\n";
            }
            if($this->items[$i]->date!=""){
                $itemdate=new feeddate($this->items[$i]->date);
                $feed.= "            <pubdate>".htmlspecialchars($itemdate->rfc822())."</pubdate>\n";
            }
            if($this->items[$i]->guid!=""){
                $feed.= "            <guid>".htmlspecialchars($this->items[$i]->guid)."</guid>\n";
            }
            $feed.= $this->_createadditionalelements($this->items[$i]->additionalelements,"        ");
            $feed.= "        </item>\n";
        }
        $feed.= "    </channel>\n";
        $feed.= "</rss>\n";
        return $feed;
    }
}
 
class rsscreator20 extends rsscreator091{
 
    function rsscreator20(){
        parent::_setrssversion("2.0");
    }
}

使用示例:
复制代码 代码如下:
<?php
header('content-type:text/html; charset=utf-8');
$db=mysql_connect('127.0.0.1','root','123456');
mysql_query("set names utf8");
mysql_select_db('dbname',$db);
$brs=mysql_query('select * from article order by add_time desc limit 0,10',$db);
$rss=new universalfeedcreator();
$rss->title="页面标题";
$rss->link="网址http://";
$rss->description="rss标题";
while($rowbrs=mysql_fetch_array($brs)){
    $item=new feeditem();
    $item->title =$rowbrs['subject'];
    $item->link='//www.jb51.net/';
    $item->description =$rowbrs['description'];
    $rss->additem($item);
}
mysql_close($db);
$rss->savefeed("rss2.0","rss.xml");

希望本文所述对大家的php程序设计有所帮助。