php生成RSS订阅示例

php生成RSSRSS(简易信息聚合,也叫聚合内容)是一种描述和同步网站内容的格式。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 文件的内容示例:

  1. <?xml version="1.0" encoding="utf-8"?> 
  2. <rss version="2.0"> 
  3. <channel> 
  4. <title>代码家园</title> 
  5. <link>http://www.daimajiayuan.com/</link> 
  6. <description>代码家园</description> 
  7. <item> 
  8. <title>RSS Tutorial</title> 
  9. <link>网站地址/rss</link> 
  10. <description>New RSS tutorial on W3School</description> 
  11. </item> 
  12. <item> 
  13. <title>XML Tutorial</title> 
  14. <link>网站地址/xml</link> 
  15. <description>New XML tutorial on W3School</description> 
  16. </item> 
  17. </channel> 
  18. </rss> 

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

  1. <?php 
  2. /** 
  3. ** php 动态生成 RSS 类 
  4. **/ 
  5. define("TIME_ZONE",""); 
  6. define("FEEDCREATOR_VERSION","www.daimajiayuan.com");//您的网址 
  7. class FeedItem extends HtmlDescribable{ 
  8.     var $title,$description,$link
  9.     var $author,$authorEmail,$image,$category,$comments,$guid,$source,$creator
  10.     var $date
  11.     var $additionalElements=Array(); 
  12.  
  13. class FeedImage extends HtmlDescribable{ 
  14.     var $title,$url,$link
  15.     var $width,$height,$description
  16.  
  17. class HtmlDescribable{ 
  18.     var $descriptionHtmlSyndicated
  19.     var $descriptionTruncSize
  20.  
  21.     function getDescription(){ 
  22.         $descriptionField=new FeedHtmlField($this->description); 
  23.         $descriptionField->syndicateHtml=$this->descriptionHtmlSyndicated; 
  24.         $descriptionField->truncSize=$this->descriptionTruncSize; 
  25.         return $descriptionField->output(); 
  26.     } 
  27.  
  28. class FeedHtmlField{ 
  29.     var $rawFieldContent
  30.     var $truncSize,$syndicateHtml
  31.     function FeedHtmlField($parFieldContent){ 
  32.         if($parFieldContent){ 
  33.             $this->rawFieldContent=$parFieldContent
  34.         } 
  35.     } 
  36.     function output(){ 
  37.         if(!$this->rawFieldContent){ 
  38.             $result=""
  39.         }    elseif($this->syndicateHtml){ 
  40.             $result="<![CDATA[".$this->rawFieldContent."]]>"
  41.         }else
  42.             if($this->truncSize and is_int($this->truncSize)){ 
  43.                 $result=FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize); 
  44.             }else
  45.                 $result=htmlspecialchars($this->rawFieldContent); 
  46.             } 
  47.         } 
  48.         return $result
  49.     } 
  50.  
  51.  
  52. class UniversalFeedCreator extends FeedCreator{ 
  53.     var $_feed
  54.  
  55.     function _setFormat($format){ 
  56.         switch (strtoupper($format)){ 
  57.             case "2.0"
  58.                 // fall through 
  59.             case "RSS2.0"
  60.                 $this->_feed=new RSSCreator20(); 
  61.                 break
  62.             case "0.91"
  63.                 // fall through 
  64.             case "RSS0.91"
  65.                 $this->_feed=new RSSCreator091(); 
  66.                 break
  67.             default
  68.                 $this->_feed=new RSSCreator091(); 
  69.                 break
  70.         } 
  71.  
  72.         $vars=get_object_vars($this); 
  73.         foreach ($vars as $key => $value){ 
  74.             // prevent overwriting of properties "contentType","encoding"; do not copy "_feed" itself 
  75.             if(!in_array($keyarray("_feed","contentType","encoding"))){ 
  76.                 $this->_feed->{$key}=$this->{$key}; 
  77.             } 
  78.         } 
  79.     } 
  80.  
  81.     function createFeed($format="RSS0.91"){ 
  82.         $this->_setFormat($format); 
  83.         return $this->_feed->createFeed(); 
  84.     } 
  85.  
  86.     function saveFeed($format="RSS0.91",$filename="",$displayContents=true){ 
  87.         $this->_setFormat($format); 
  88.         $this->_feed->saveFeed($filename,$displayContents); 
  89.     } 
  90.  
  91.     function useCached($format="RSS0.91",$filename="",$timeout=3600){ 
  92.         $this->_setFormat($format); 
  93.         $this->_feed->useCached($filename,$timeout); 
  94.     } 
  95.  
  96.  
  97. class FeedCreator extends HtmlDescribable{ 
  98.     var $title,$description,$link
  99.     var $syndicationURL,$image,$language,$copyright,$pubDate,$lastBuildDate,$editor,$editorEmail,$webmaster,$category,$docs,$ttl,$rating,$skipHours,$skipDays
  100.     var $xslStyleSheet=""
  101.     var $items=Array(); 
  102.     var $contentType="application/xml"
  103.     var $encoding="utf-8"
  104.     var $additionalElements=Array(); 
  105.  
  106.     function addItem($item){ 
  107.         $this->items[]=$item
  108.     } 
  109.  
  110.     function clearItem2Null(){ 
  111.         $this->items=array(); 
  112.     } 
  113.  
  114.     function iTrunc($string,$length){ 
  115.         if(strlen($string)<=$length){ 
  116.             return $string
  117.         } 
  118.  
  119.         $pos=strrpos($string,"."); 
  120.         if($pos>=$length-4){ 
  121.             $string=substr($string,0,$length-4); 
  122.             $pos=strrpos($string,"."); 
  123.         } 
  124.         if($pos>=$length*0.4){ 
  125.             return substr($string,0,$pos+1)." ..."
  126.         } 
  127.  
  128.         $pos=strrpos($string," "); 
  129.         if($pos>=$length-4){ 
  130.             $string=substr($string,0,$length-4); 
  131.             $pos=strrpos($string," "); 
  132.         } 
  133.         if($pos>=$length*0.4){ 
  134.             return substr($string,0,$pos)." ..."
  135.         } 
  136.  
  137.         return substr($string,0,$length-4)." ..."
  138.     } 
  139.  
  140.  
  141.     function _createGeneratorComment(){ 
  142.         return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n"
  143.     } 
  144.  
  145.     function _createAdditionalElements($elements,$indentString=""){ 
  146.         $ae=""
  147.         if(is_array($elements)){ 
  148.             foreach($elements AS $key => $value){ 
  149.                 $ae.= $indentString."<$key>$value</$key>\n"
  150.             } 
  151.         } 
  152.         return $ae
  153.     } 
  154.  
  155.     function _createStylesheetReferences(){ 
  156.         $xml=""
  157.         if($this->cssStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n"
  158.         if($this->xslStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n"
  159.         return $xml
  160.     } 
  161.  
  162.     function createFeed(){} 
  163.  
  164.     function _generateFilename(){ 
  165.         $fileInfo=pathinfo($_SERVER["PHP_SELF"]); 
  166.         return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml"
  167.     } 
  168.  
  169.     function _redirect($filename){ 
  170.         Header("Content-Type: ".$this->contentType."; charset=".$this->encoding."; filename=".basename($filename)); 
  171.         Header("Content-Disposition: inline; filename=".basename($filename)); 
  172.         readfile($filename,"r"); 
  173.         die(); 
  174.     } 
  175.  
  176.     function useCached($filename="",$timeout=3600){ 
  177.         $this->_timeout=$timeout
  178.         if($filename==""){ 
  179.             $filename=$this->_generateFilename(); 
  180.         } 
  181.         if(file_exists($filename) && (time()-filemtime($filename) < $timeout)){ 
  182.             $this->_redirect($filename); 
  183.         } 
  184.     } 
  185.  
  186.     function saveFeed($filename="",$displayContents=true){ 
  187.         if($filename==""){ 
  188.             $filename=$this->_generateFilename(); 
  189.         } 
  190.         $feedFile=fopen($filename,"w+"); 
  191.         if($feedFile){ 
  192.             fputs($feedFile,$this->createFeed()); 
  193.             fclose($feedFile); 
  194.             if($displayContents){ 
  195.                 $this->_redirect($filename); 
  196.             } 
  197.         }else
  198.             echo "<br /><b>Error creating feed file, please check write permissions.</b><br />"
  199.         } 
  200.     } 
  201.  
  202.  
  203. class FeedDate{ 
  204.     var $unix
  205.     function FeedDate($dateString=""){ 
  206.         if($dateString==""$dateString=date("r"); 
  207.  
  208.         if(is_integer($dateString)){ 
  209.             $this->unix=$dateString
  210.             return
  211.         } 
  212.         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)){ 
  213.             $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); 
  214.             $this->unix=mktime($matches[4],$matches[5],$matches[6],$months[$matches[2]],$matches[1],$matches[3]); 
  215.             if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ 
  216.                 $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; 
  217.             }else
  218.                 if(strlen($matches[7])==1){ 
  219.                     $oneHour=3600; 
  220.                     $ord=ord($matches[7]); 
  221.                     if($ord < ord("M")){ 
  222.                         $tzOffset=(ord("A") - $ord - 1) * $oneHour
  223.                     } elseif($ord >= ord("M") && $matches[7]!="Z"){ 
  224.                         $tzOffset=($ord - ord("M")) * $oneHour
  225.                     } elseif($matches[7]=="Z"){ 
  226.                         $tzOffset=0; 
  227.                     } 
  228.                 } 
  229.                 switch ($matches[7]){ 
  230.                     case "UT"
  231.                     case "GMT":    $tzOffset=0; 
  232.                 } 
  233.             } 
  234.             $this->unix += $tzOffset
  235.             return
  236.         } 
  237.         if(preg_match("~(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(.*)~",$dateString,$matches)){ 
  238.             $this->unix=mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]); 
  239.             if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){ 
  240.                 $tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60; 
  241.             }else
  242.                 if($matches[7]=="Z"){ 
  243.                     $tzOffset=0; 
  244.                 } 
  245.             } 
  246.             $this->unix += $tzOffset
  247.             return
  248.         } 
  249.         $this->unix=0; 
  250.     } 
  251.  
  252.     function rfc822(){ 
  253.         $date=gmdate("Y-m-d H:i:s",$this->unix); 
  254.         if(TIME_ZONE!=""$date .= " ".str_replace(":","",TIME_ZONE); 
  255.         return $date
  256.     } 
  257.  
  258.     function iso8601(){ 
  259.         $date=gmdate("Y-m-d H:i:s",$this->unix); 
  260.         $date=substr($date,0,22) . ':' . substr($date,-2); 
  261.         if(TIME_ZONE!=""$date=str_replace("+00:00",TIME_ZONE,$date); 
  262.         return $date
  263.     } 
  264.  
  265.     function unix(){ 
  266.         return $this->unix; 
  267.     } 
  268.  
  269. class RSSCreator10 extends FeedCreator{ 
  270.     function createFeed(){ 
  271.         $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"
  272.         $feed.= $this->_createGeneratorComment(); 
  273.         if($this->cssStyleSheet==""){ 
  274.             $cssStyleSheet="http://www.w3.org/2000/08/w3c-synd/style.css"
  275.         } 
  276.         $feed.= $this->_createStylesheetReferences(); 
  277.         $feed.= "<rdf:RDF\n"
  278.         $feed.= "    xmlns=\"http://purl.org/rss/1.0/\"\n"
  279.         $feed.= "    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n"
  280.         $feed.= "    xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n"
  281.         $feed.= "    xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n"
  282.         $feed.= "    <channel rdf:about=\"".$this->syndicationURL."\">\n"
  283.         $feed.= "        <title>".htmlspecialchars($this->title)."</title>\n"
  284.         $feed.= "        <description>".htmlspecialchars($this->description)."</description>\n"
  285.         $feed.= "        <link>".$this->link."</link>\n"
  286.         if($this->image!=null){ 
  287.             $feed.= "        <image rdf:resource=\"".$this->image->url."\" />\n"
  288.         } 
  289.         $now=new FeedDate(); 
  290.         $feed.= "       <dc:date>".htmlspecialchars($now->iso8601())."</dc:date>\n"
  291.         $feed.= "        <items>\n"
  292.         $feed.= "            <rdf:Seq>\n"
  293.         for ($i=0;$i<count($this->items);$i++){ 
  294.             $feed.= "                <rdf:li rdf:resource=\"".htmlspecialchars($this->items[$i]->link)."\"/>\n"
  295.         } 
  296.         $feed.= "            </rdf:Seq>\n"
  297.         $feed.= "        </items>\n"
  298.         $feed.= "    </channel>\n"
  299.         if($this->image!=null){ 
  300.             $feed.= "    <image rdf:about=\"".$this->image->url."\">\n"
  301.             $feed.= "        <title>".$this->image->title."</title>\n"
  302.             $feed.= "        <link>".$this->image->link."</link>\n"
  303.             $feed.= "        <url>".$this->image->url."</url>\n"
  304.             $feed.= "    </image>\n"
  305.         } 
  306.         $feed.= $this->_createAdditionalElements($this->additionalElements,"    "); 
  307.  
  308.         for ($i=0;$i<count($this->items);$i++){ 
  309.             $feed.= "    <item rdf:about=\"".htmlspecialchars($this->items[$i]->link)."\">\n"
  310.             //$feed.= "        <dc:type>Posting</dc:type>\n"; 
  311.             $feed.= "        <dc:format>text/html</dc:format>\n"
  312.             if($this->items[$i]->date!=null){ 
  313.                 $itemDate=new FeedDate($this->items[$i]->date); 
  314.                 $feed.= "        <dc:date>".htmlspecialchars($itemDate->iso8601())."</dc:date>\n"
  315.             } 
  316.             if($this->items[$i]->source!=""){ 
  317.                 $feed.= "        <dc:source>".htmlspecialchars($this->items[$i]->source)."</dc:source>\n"
  318.             } 
  319.             if($this->items[$i]->author!=""){ 
  320.                 $feed.= "        <dc:creator>".htmlspecialchars($this->items[$i]->author)."</dc:creator>\n"
  321.             } 
  322.             $feed.= "        <title>".htmlspecialchars(strip_tags(strtr($this->items[$i]->title,"\n\r","  ")))."</title>\n"
  323.             $feed.= "        <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"
  324.             $feed.= "        <description>".htmlspecialchars($this->items[$i]->description)."</description>\n"
  325.             $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements,"        "); 
  326.             $feed.= "    </item>\n"
  327.         } 
  328.         $feed.= "</rdf:RDF>\n"
  329.         return $feed
  330.     } 
  331.  
  332. class RSSCreator091 extends FeedCreator{ 
  333.     var $RSSVersion
  334.  
  335.     function RSSCreator091(){ 
  336.         $this->_setRSSVersion("0.91"); 
  337.         $this->contentType="application/rss+xml"
  338.     } 
  339.  
  340.     function _setRSSVersion($version){ 
  341.         $this->RSSVersion=$version
  342.     } 
  343.  
  344.     function createFeed(){ 
  345.         $feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n"
  346.         $feed.= $this->_createGeneratorComment(); 
  347.         $feed.= $this->_createStylesheetReferences(); 
  348.         $feed.= "<rss version=\"".$this->RSSVersion."\">\n"
  349.         $feed.= "    <channel>\n"
  350.         $feed.= "        <title>".FeedCreator::iTrunc(htmlspecialchars($this->title),100)."</title>\n"
  351.         $this->descriptionTruncSize=500; 
  352.         $feed.= "        <description>".$this->getDescription()."</description>\n"
  353.         $feed.= "        <link>".$this->link."</link>\n"
  354.         $now=new FeedDate(); 
  355.         $feed.= "        <lastBuildDate>".htmlspecialchars($now->rfc822())."</lastBuildDate>\n"
  356.         $feed.= "        <generator>".FEEDCREATOR_VERSION."</generator>\n"
  357.  
  358.         if($this->image!=null){ 
  359.             $feed.= "        <image>\n"
  360.             $feed.= "            <url>".$this->image->url."</url>\n"
  361.             $feed.= "            <title>".FeedCreator::iTrunc(htmlspecialchars($this->image->title),100)."</title>\n"
  362.             $feed.= "            <link>".$this->image->link."</link>\n"
  363.             if($this->image->width!=""){ 
  364.                 $feed.= "            <width>".$this->image->width."</width>\n"
  365.             } 
  366.             if($this->image->height!=""){ 
  367.                 $feed.= "            <height>".$this->image->height."</height>\n"
  368.             } 
  369.             if($this->image->description!=""){ 
  370.                 $feed.= "            <description>".$this->image->getDescription()."</description>\n"
  371.             } 
  372.             $feed.= "        </image>\n"
  373.         } 
  374.         if($this->language!=""){ 
  375.             $feed.= "        <language>".$this->language."</language>\n"
  376.         } 
  377.         if($this->copyright!=""){ 
  378.             $feed.= "        <copyright>".FeedCreator::iTrunc(htmlspecialchars($this->copyright),100)."</copyright>\n"
  379.         } 
  380.         if($this->editor!=""){ 
  381.             $feed.= "        <managingEditor>".FeedCreator::iTrunc(htmlspecialchars($this->editor),100)."</managingEditor>\n"
  382.         } 
  383.         if($this->webmaster!=""){ 
  384.             $feed.= "        <webMaster>".FeedCreator::iTrunc(htmlspecialchars($this->webmaster),100)."</webMaster>\n"
  385.         } 
  386.         if($this->pubDate!=""){ 
  387.             $pubDate=new FeedDate($this->pubDate); 
  388.             $feed.= "        <pubDate>".htmlspecialchars($pubDate->rfc822())."</pubDate>\n"
  389.         } 
  390.         if($this->category!=""){ 
  391.             $feed.= "        <category>".htmlspecialchars($this->category)."</category>\n"
  392.         } 
  393.         if($this->docs!=""){ 
  394.             $feed.= "        <docs>".FeedCreator::iTrunc(htmlspecialchars($this->docs),500)."</docs>\n"
  395.         } 
  396.         if($this->ttl!=""){ 
  397.             $feed.= "        <ttl>".htmlspecialchars($this->ttl)."</ttl>\n"
  398.         } 
  399.         if($this->rating!=""){ 
  400.             $feed.= "        <rating>".FeedCreator::iTrunc(htmlspecialchars($this->rating),500)."</rating>\n"
  401.         } 
  402.         if($this->skipHours!=""){ 
  403.             $feed.= "        <skipHours>".htmlspecialchars($this->skipHours)."</skipHours>\n"
  404.         } 
  405.         if($this->skipDays!=""){ 
  406.             $feed.= "        <skipDays>".htmlspecialchars($this->skipDays)."</skipDays>\n"
  407.         } 
  408.         $feed.= $this->_createAdditionalElements($this->additionalElements,"    "); 
  409.  
  410.         for ($i=0;$i<count($this->items);$i++){ 
  411.             $feed.= "        <item>\n"
  412.             $feed.= "            <title>".FeedCreator::iTrunc(htmlspecialchars(strip_tags($this->items[$i]->title)),100)."</title>\n"
  413.             $feed.= "            <link>".htmlspecialchars($this->items[$i]->link)."</link>\n"
  414.             $feed.= "            <description>".$this->items[$i]->getDescription()."</description>\n"
  415.  
  416.             if($this->items[$i]->author!=""){ 
  417.                 $feed.= "            <author>".htmlspecialchars($this->items[$i]->author)."</author>\n"
  418.             } 
  419.             /* 
  420.              // on hold 
  421.              if($this->items[$i]->source!=""){ 
  422.              $feed.= "            <source>".htmlspecialchars($this->items[$i]->source)."</source>\n"; 
  423.              } 
  424.              */ 
  425.             if($this->items[$i]->category!=""){ 
  426.                 $feed.= "            <category>".htmlspecialchars($this->items[$i]->category)."</category>\n"
  427.             } 
  428.             if($this->items[$i]->comments!=""){ 
  429.                 $feed.= "            <comments>".htmlspecialchars($this->items[$i]->comments)."</comments>\n"
  430.             } 
  431.             if($this->items[$i]->date!=""){ 
  432.                 $itemDate=new FeedDate($this->items[$i]->date); 
  433.                 $feed.= "            <pubDate>".htmlspecialchars($itemDate->rfc822())."</pubDate>\n"
  434.             } 
  435.             if($this->items[$i]->guid!=""){ 
  436.                 $feed.= "            <guid>".htmlspecialchars($this->items[$i]->guid)."</guid>\n"
  437.             } 
  438.             $feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements,"        "); 
  439.             $feed.= "        </item>\n"
  440.         } 
  441.         $feed.= "    </channel>\n"
  442.         $feed.= "</rss>\n"
  443.         return $feed
  444.     } 
  445.  
  446. class RSSCreator20 extends RSSCreator091{ 
  447.  
  448.     function RSSCreator20(){ 
  449.         parent::_setRSSVersion("2.0"); 
  450.     } 
  451.  

使用示例:

  1. <?php 
  2. header('Content-Type:text/html; charset=utf-8'); 
  3. $db=mysql_connect('127.0.0.1','root','123456'); 
  4. mysql_query("set names utf8"); 
  5. mysql_select_db('dbname',$db); 
  6. $brs=mysql_query('select * from article order by add_time desc limit 0,10',$db); 
  7. $rss=new UniversalFeedCreator(); 
  8. $rss->title="页面标题"
  9. $rss->link="网址http://"
  10. $rss->description="rss标题"
  11. while($rowbrs=mysql_fetch_array($brs)){ 
  12.     $item=new FeedItem(); 
  13.     $item->title =$rowbrs['subject']; 
  14.     $item->link='http://www.daimajiayuan.com/'
  15.     $item->description =$rowbrs['description']; 
  16.     $rss->addItem($item); 
  17. mysql_close($db); 
  18. $rss->saveFeed("RSS2.0","rss.xml"); 

转载请注明:代码家园 » php生成RSS订阅示例

也许你会喜欢和关注与本文内容高度相关的文章:

实例代码:使用PHP调用Twitter的RSS

评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)