首页 > 后端开发 > php教程 > php生成RSS订阅类

php生成RSS订阅类

WBOY
发布: 2016-06-20 13:04:05
原创
976 人浏览过

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

<p><?php</p>/**<br />** php 动态生成 RSS 类<br />**/<br />define("TIME_ZONE","");<br />define("FEEDCREATOR_VERSION","www.scutephp.com");//您的网址<br />class FeedItem extends HtmlDescribable{<br />	var $title,$description,$link;<br />	var $author,$authorEmail,$image,$category,$comments,$guid,$source,$creator;<br />	var $date;<br />	var $additionalElements=Array();<br />}<br /><br />class FeedImage extends HtmlDescribable{<br />	var $title,$url,$link;<br />	var $width,$height,$description;<br />}<br /><br />class HtmlDescribable{<br />	var $descriptionHtmlSyndicated;<br />	var $descriptionTruncSize;<br /><br />	function getDescription(){<br />		$descriptionField=new FeedHtmlField($this->description);<br />		$descriptionField->syndicateHtml=$this->descriptionHtmlSyndicated;<br />		$descriptionField->truncSize=$this->descriptionTruncSize;<br />		return $descriptionField->output();<br />	}<br />}<br /><br />class FeedHtmlField{<br />	var $rawFieldContent;<br />	var $truncSize,$syndicateHtml;<br />	function FeedHtmlField($parFieldContent){<br />		if($parFieldContent){<br />			$this->rawFieldContent=$parFieldContent;<br />		}<br />	}<br />	function output(){<br />		if(!$this->rawFieldContent){<br />			$result="";<br />		}    elseif($this->syndicateHtml){<br />			$result="<![CDATA[".$this->rawFieldContent."]]>";<br />		}else{<br />			if($this->truncSize and is_int($this->truncSize)){<br />				$result=FeedCreator::iTrunc(htmlspecialchars($this->rawFieldContent),$this->truncSize);<br />			}else{<br />				$result=htmlspecialchars($this->rawFieldContent);<br />			}<br />		}<br />		return $result;<br />	}<br /><br />}<br /><br />class UniversalFeedCreator extends FeedCreator{<br />	var $_feed;<br /><br />	function _setFormat($format){<br />		switch (strtoupper($format)){<br />			case "2.0":<br />				// fall through<br />			case "RSS2.0":<br />				$this->_feed=new RSSCreator20();<br />				break;<br />			case "0.91":<br />				// fall through<br />			case "RSS0.91":<br />				$this->_feed=new RSSCreator091();<br />				break;<br />			default:<br />				$this->_feed=new RSSCreator091();<br />				break;<br />		}<br /><br />		$vars=get_object_vars($this);<br />		foreach ($vars as $key => $value){<br />			// prevent overwriting of properties "contentType","encoding"; do not copy "_feed" itself<br />			if(!in_array($key, array("_feed","contentType","encoding"))){<br />				$this->_feed->{$key}=$this->{$key};<br />			}<br />		}<br />	}<br /><br />	function createFeed($format="RSS0.91"){<br />		$this->_setFormat($format);<br />		return $this->_feed->createFeed();<br />	}<br /><br />	function saveFeed($format="RSS0.91",$filename="",$displayContents=true){<br />		$this->_setFormat($format);<br />		$this->_feed->saveFeed($filename,$displayContents);<br />	}<br /><br />	function useCached($format="RSS0.91",$filename="",$timeout=3600){<br />		$this->_setFormat($format);<br />		$this->_feed->useCached($filename,$timeout);<br />	}<br /><br />}<br /><br />class FeedCreator extends HtmlDescribable{<br />	var $title,$description,$link;<br />	var $syndicationURL,$image,$language,$copyright,$pubDate,$lastBuildDate,$editor,$editorEmail,$webmaster,$category,$docs,$ttl,$rating,$skipHours,$skipDays;<br />	var $xslStyleSheet="";<br />	var $items=Array();<br />	var $contentType="application/xml";<br />	var $encoding="utf-8";<br />	var $additionalElements=Array();<br /><br />	function addItem($item){<br />		$this->items[]=$item;<br />	}<br /><br />	function clearItem2Null(){<br />		$this->items=array();<br />	}<br /><br />	function iTrunc($string,$length){<br />		if(strlen($string)<=$length){<br />			return $string;<br />		}<br /><br />		$pos=strrpos($string,".");<br />		if($pos>=$length-4){<br />			$string=substr($string,0,$length-4);<br />			$pos=strrpos($string,".");<br />		}<br />		if($pos>=$length*0.4){<br />			return substr($string,0,$pos+1)." ...";<br />		}<br /><br />		$pos=strrpos($string," ");<br />		if($pos>=$length-4){<br />			$string=substr($string,0,$length-4);<br />			$pos=strrpos($string," ");<br />		}<br />		if($pos>=$length*0.4){<br />			return substr($string,0,$pos)." ...";<br />		}<br /><br />		return substr($string,0,$length-4)." ...";<br />	}<br /><br /><br />	function _createGeneratorComment(){<br />		return "<!-- generator=\"".FEEDCREATOR_VERSION."\" -->\n";<br />	}<br /><br />	function _createAdditionalElements($elements,$indentString=""){<br />		$ae="";<br />		if(is_array($elements)){<br />			foreach($elements AS $key => $value){<br />				$ae.= $indentString."<$key>$value</$key>\n";<br />			}<br />		}<br />		return $ae;<br />	}<br /><br />	function _createStylesheetReferences(){<br />		$xml="";<br />		if($this->cssStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->cssStyleSheet."\" type=\"text/css\"?>\n";<br />		if($this->xslStyleSheet) $xml .= "<?xml-stylesheet href=\"".$this->xslStyleSheet."\" type=\"text/xsl\"?>\n";<br />		return $xml;<br />	}<br /><br />	function createFeed(){}<br /><br />	function _generateFilename(){<br />		$fileInfo=pathinfo($_SERVER["PHP_SELF"]);<br />		return substr($fileInfo["basename"],0,-(strlen($fileInfo["extension"])+1)).".xml";<br />	}<br /><br />	function _redirect($filename){<br />		Header("Content-Type: ".$this->contentType."; charset=".$this->encoding."; filename=".basename($filename));<br />		Header("Content-Disposition: inline; filename=".basename($filename));<br />		readfile($filename,"r");<br />		die();<br />	}<br /><br />	function useCached($filename="",$timeout=3600){<br />		$this->_timeout=$timeout;<br />		if($filename==""){<br />			$filename=$this->_generateFilename();<br />		}<br />		if(file_exists($filename) && (time()-filemtime($filename) < $timeout)){<br />			$this->_redirect($filename);<br />		}<br />	}<br /><br />	function saveFeed($filename="",$displayContents=true){<br />		if($filename==""){<br />			$filename=$this->_generateFilename();<br />		}<br />		$feedFile=fopen($filename,"w+");<br />		if($feedFile){<br />			fputs($feedFile,$this->createFeed());<br />			fclose($feedFile);<br />			if($displayContents){<br />				$this->_redirect($filename);<br />			}<br />		}else{<br />			echo "<br /><b>Error creating feed file, please check write permissions.</b><br />";<br />		}<br />	}<br /><br />}<br /><br />class FeedDate{<br />	var $unix;<br />	function FeedDate($dateString=""){<br />		if($dateString=="") $dateString=date("r");<br /><br />		if(is_integer($dateString)){<br />			$this->unix=$dateString;<br />			return;<br />		}<br />		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)){<br />			$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);<br />			$this->unix=mktime($matches[4],$matches[5],$matches[6],$months[$matches[2]],$matches[1],$matches[3]);<br />			if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){<br />				$tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60;<br />			}else{<br />				if(strlen($matches[7])==1){<br />					$oneHour=3600;<br />					$ord=ord($matches[7]);<br />					if($ord < ord("M")){<br />						$tzOffset=(ord("A") - $ord - 1) * $oneHour;<br />					} elseif($ord >= ord("M") && $matches[7]!="Z"){<br />						$tzOffset=($ord - ord("M")) * $oneHour;<br />					} elseif($matches[7]=="Z"){<br />						$tzOffset=0;<br />					}<br />				}<br />				switch ($matches[7]){<br />					case "UT":<br />					case "GMT":    $tzOffset=0;<br />				}<br />			}<br />			$this->unix += $tzOffset;<br />			return;<br />		}<br />		if(preg_match("~(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})(.*)~",$dateString,$matches)){<br />			$this->unix=mktime($matches[4],$matches[5],$matches[6],$matches[2],$matches[3],$matches[1]);<br />			if(substr($matches[7],0,1)=='+' OR substr($matches[7],0,1)=='-'){<br />				$tzOffset=(substr($matches[7],0,3) * 60 + substr($matches[7],-2)) * 60;<br />			}else{<br />				if($matches[7]=="Z"){<br />					$tzOffset=0;<br />				}<br />			}<br />			$this->unix += $tzOffset;<br />			return;<br />		}<br />		$this->unix=0;<br />	}<br /><br />	function rfc822(){<br />		$date=gmdate("Y-m-d H:i:s",$this->unix);<br />		if(TIME_ZONE!="") $date .= " ".str_replace(":","",TIME_ZONE);<br />		return $date;<br />	}<br /><br />	function iso8601(){<br />		$date=gmdate("Y-m-d H:i:s",$this->unix);<br />		$date=substr($date,0,22) . ':' . substr($date,-2);<br />		if(TIME_ZONE!="") $date=str_replace("+00:00",TIME_ZONE,$date);<br />		return $date;<br />	}<br /><br />	function unix(){<br />		return $this->unix;<br />	}<br />}<br /><br />class RSSCreator10 extends FeedCreator{<br />	function createFeed(){<br />		$feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n";<br />		$feed.= $this->_createGeneratorComment();<br />		if($this->cssStyleSheet==""){<br />			$cssStyleSheet="http://www.w3.org/2000/08/w3c-synd/style.css";<br />		}<br />		$feed.= $this->_createStylesheetReferences();<br />		$feed.= "<rdf:RDF\n";<br />		$feed.= "    xmlns=\"http://purl.org/rss/1.0/\"\n";<br />		$feed.= "    xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\n";<br />		$feed.= "    xmlns:slash=\"http://purl.org/rss/1.0/modules/slash/\"\n";<br />		$feed.= "    xmlns:dc=\"http://purl.org/dc/elements/1.1/\">\n";<br />		$feed.= "    <channel rdf:about=\"".$this->syndicationURL."\">\n";<br />		$feed.= "        <title>".htmlspecialchars($this->title)."</title>\n";<br />		$feed.= "        <description>".htmlspecialchars($this->description)."</description>\n";<br />		$feed.= "        <link>".$this->link."</link>\n";<br />		if($this->image!=null){<br />			$feed.= "        <image rdf:resource=\"".$this->image->url."\" />\n";<br />		}<br />		$now=new FeedDate();<br />		$feed.= "       <dc:date>".htmlspecialchars($now->iso8601())."</dc:date>\n";<br />		$feed.= "        <items>\n";<br />		$feed.= "            <rdf:Seq>\n";<br />		for ($i=0;$i<count($this->items);$i++){<br />			$feed.= "                <rdf:li rdf:resource=\"".htmlspecialchars($this->items[$i]->link)."\"/>\n";<br />		}<br />		$feed.= "            </rdf:Seq>\n";<br />		$feed.= "        </items>\n";<br />		$feed.= "    </channel>\n";<br />		if($this->image!=null){<br />			$feed.= "    <image rdf:about=\"".$this->image->url."\">\n";<br />			$feed.= "        <title>".$this->image->title."</title>\n";<br />			$feed.= "        <link>".$this->image->link."</link>\n";<br />			$feed.= "        <url>".$this->image->url."</url>\n";<br />			$feed.= "    </image>\n";<br />		}<br />		$feed.= $this->_createAdditionalElements($this->additionalElements,"    ");<br /><br />		for ($i=0;$i<count($this->items);$i++){<br />			$feed.= "    <item rdf:about=\"".htmlspecialchars($this->items[$i]->link)."\">\n";<br />			//$feed.= "        <dc:type>Posting</dc:type>\n";<br />			$feed.= "        <dc:format>text/html</dc:format>\n";<br />			if($this->items[$i]->date!=null){<br />				$itemDate=new FeedDate($this->items[$i]->date);<br />				$feed.= "        <dc:date>".htmlspecialchars($itemDate->iso8601())."</dc:date>\n";<br />			}<br />			if($this->items[$i]->source!=""){<br />				$feed.= "        <dc:source>".htmlspecialchars($this->items[$i]->source)."</dc:source>\n";<br />			}<br />			if($this->items[$i]->author!=""){<br />				$feed.= "        <dc:creator>".htmlspecialchars($this->items[$i]->author)."</dc:creator>\n";<br />			}<br />			$feed.= "        <title>".htmlspecialchars(strip_tags(strtr($this->items[$i]->title,"\n\r","  ")))."</title>\n";<br />			$feed.= "        <link>".htmlspecialchars($this->items[$i]->link)."</link>\n";<br />			$feed.= "        <description>".htmlspecialchars($this->items[$i]->description)."</description>\n";<br />			$feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements,"        ");<br />			$feed.= "    </item>\n";<br />		}<br />		$feed.= "</rdf:RDF>\n";<br />		return $feed;<br />	}<br />}<br /><br />class RSSCreator091 extends FeedCreator{<br />	var $RSSVersion;<br /><br />	function RSSCreator091(){<br />		$this->_setRSSVersion("0.91");<br />		$this->contentType="application/rss+xml";<br />	}<br /><br />	function _setRSSVersion($version){<br />		$this->RSSVersion=$version;<br />	}<br /><br />	function createFeed(){<br />		$feed="<?xml version=\"1.0\" encoding=\"".$this->encoding."\"?>\n";<br />		$feed.= $this->_createGeneratorComment();<br />		$feed.= $this->_createStylesheetReferences();<br />		$feed.= "<rss version=\"".$this->RSSVersion."\">\n";<br />		$feed.= "    <channel>\n";<br />		$feed.= "        <title>".FeedCreator::iTrunc(htmlspecialchars($this->title),100)."</title>\n";<br />		$this->descriptionTruncSize=500;<br />		$feed.= "        <description>".$this->getDescription()."</description>\n";<br />		$feed.= "        <link>".$this->link."</link>\n";<br />		$now=new FeedDate();<br />		$feed.= "        <lastBuildDate>".htmlspecialchars($now->rfc822())."</lastBuildDate>\n";<br />		$feed.= "        <generator>".FEEDCREATOR_VERSION."</generator>\n";<br /><br />		if($this->image!=null){<br />			$feed.= "        <image>\n";<br />			$feed.= "            <url>".$this->image->url."</url>\n";<br />			$feed.= "            <title>".FeedCreator::iTrunc(htmlspecialchars($this->image->title),100)."</title>\n";<br />			$feed.= "            <link>".$this->image->link."</link>\n";<br />			if($this->image->width!=""){<br />				$feed.= "            <width>".$this->image->width."</width>\n";<br />			}<br />			if($this->image->height!=""){<br />				$feed.= "            <height>".$this->image->height."</height>\n";<br />			}<br />			if($this->image->description!=""){<br />				$feed.= "            <description>".$this->image->getDescription()."</description>\n";<br />			}<br />			$feed.= "        </image>\n";<br />		}<br />		if($this->language!=""){<br />			$feed.= "        <language>".$this->language."</language>\n";<br />		}<br />		if($this->copyright!=""){<br />			$feed.= "        <copyright>".FeedCreator::iTrunc(htmlspecialchars($this->copyright),100)."</copyright>\n";<br />		}<br />		if($this->editor!=""){<br />			$feed.= "        <managingEditor>".FeedCreator::iTrunc(htmlspecialchars($this->editor),100)."</managingEditor>\n";<br />		}<br />		if($this->webmaster!=""){<br />			$feed.= "        <webMaster>".FeedCreator::iTrunc(htmlspecialchars($this->webmaster),100)."</webMaster>\n";<br />		}<br />		if($this->pubDate!=""){<br />			$pubDate=new FeedDate($this->pubDate);<br />			$feed.= "        <pubDate>".htmlspecialchars($pubDate->rfc822())."</pubDate>\n";<br />		}<br />		if($this->category!=""){<br />			$feed.= "        <category>".htmlspecialchars($this->category)."</category>\n";<br />		}<br />		if($this->docs!=""){<br />			$feed.= "        <docs>".FeedCreator::iTrunc(htmlspecialchars($this->docs),500)."</docs>\n";<br />		}<br />		if($this->ttl!=""){<br />			$feed.= "        <ttl>".htmlspecialchars($this->ttl)."</ttl>\n";<br />		}<br />		if($this->rating!=""){<br />			$feed.= "        <rating>".FeedCreator::iTrunc(htmlspecialchars($this->rating),500)."</rating>\n";<br />		}<br />		if($this->skipHours!=""){<br />			$feed.= "        <skipHours>".htmlspecialchars($this->skipHours)."</skipHours>\n";<br />		}<br />		if($this->skipDays!=""){<br />			$feed.= "        <skipDays>".htmlspecialchars($this->skipDays)."</skipDays>\n";<br />		}<br />		$feed.= $this->_createAdditionalElements($this->additionalElements,"    ");<br /><br />		for ($i=0;$i<count($this->items);$i++){<br />			$feed.= "        <item>\n";<br />			$feed.= "            <title>".FeedCreator::iTrunc(htmlspecialchars(strip_tags($this->items[$i]->title)),100)."</title>\n";<br />			$feed.= "            <link>".htmlspecialchars($this->items[$i]->link)."</link>\n";<br />			$feed.= "            <description>".$this->items[$i]->getDescription()."</description>\n";<br /><br />			if($this->items[$i]->author!=""){<br />				$feed.= "            <author>".htmlspecialchars($this->items[$i]->author)."</author>\n";<br />			}<br />			/*<br />			 // on hold<br />			 if($this->items[$i]->source!=""){<br />			 $feed.= "            <source>".htmlspecialchars($this->items[$i]->source)."</source>\n";<br />			 }<br />			 */<br />			if($this->items[$i]->category!=""){<br />				$feed.= "            <category>".htmlspecialchars($this->items[$i]->category)."</category>\n";<br />			}<br />			if($this->items[$i]->comments!=""){<br />				$feed.= "            <comments>".htmlspecialchars($this->items[$i]->comments)."</comments>\n";<br />			}<br />			if($this->items[$i]->date!=""){<br />				$itemDate=new FeedDate($this->items[$i]->date);<br />				$feed.= "            <pubDate>".htmlspecialchars($itemDate->rfc822())."</pubDate>\n";<br />			}<br />			if($this->items[$i]->guid!=""){<br />				$feed.= "            <guid>".htmlspecialchars($this->items[$i]->guid)."</guid>\n";<br />			}<br />			$feed.= $this->_createAdditionalElements($this->items[$i]->additionalElements,"        ");<br />			$feed.= "        </item>\n";<br />		}<br />		$feed.= "    </channel>\n";<br />		$feed.= "</rss>\n";<br />		return $feed;<br />	}<br />}<br /><br />class RSSCreator20 extends RSSCreator091{<br /><br />	function RSSCreator20(){<br />		parent::_setRSSVersion("2.0");<br />	}<br /><br /><p>}
登录后复制

使用示例:

<p><?php</p>header('Content-Type:text/html; charset=utf-8');<br />$db=mysql_connect('127.0.0.1','root','123456');<br />mysql_query("set names utf8");<br />mysql_select_db('dbname',$db);<br />$brs=mysql_query('select * from article order by add_time desc limit 0,10',$db);<br />$rss=new UniversalFeedCreator();<br />$rss->title="页面标题";<br />$rss->link="网址http://";<br />$rss->description="rss标题";<br />while($rowbrs=mysql_fetch_array($brs)){<br />	$item=new FeedItem();<br />	$item->title =$rowbrs['subject'];<br />	$item->link='http://www.scutephp.com/';<br />	$item->description =$rowbrs['description'];<br />	$rss->addItem($item);<br />}<br />mysql_close($db);<br />$rss->saveFeed("RSS2.0","rss.xml");
登录后复制


相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板