PHP how to generate RSS feeds _php tutorial

Source: Internet
Author: User
Tags cdata rfc822 vars

How PHP generates an RSS feed


The example in this article describes how PHP generates RSS feeds. Share to everyone for your reference. The specific analysis is as follows:

RSS (Simple information aggregation, also known as aggregated content) is a format for describing and synchronizing site content. RSS can be one of the following three explanations: Really simple SYNDICATION;RDF (Resource Description Framework) site Summary, Rich site Summary. But in fact these three explanations refer to the same kind of syndication technology. RSS is now widely used in online news channels, blogs and wikis. Use RSS feeds to get information faster, and the website provides RSS feeds that allow users to get the latest updates on the site's content. Web users can read Web site content that supports RSS output without opening the Site content page, with the help of RSS-enabled aggregation tool software on the client.
Technically an RSS file is a canonical XML data, which is usually rss,xml or RDF as a suffix, here is an example of an RSS file content:

The code is as follows:




Home of the script
http://www.jb51.net/
Home of the script

RSS Tutorial
Website address/rss
New RSS tutorial on W3school


XML Tutorial
Website address/xml
New XML tutorial on W3school


Here's a sample code that dynamically generates RSS using PHP:

The code is as follows:

/**
* * PHP dynamically generated RSS class
**/
Define ("Time_zone", "" ");
Define ("Feedcreator_version", "www.jb51.net");//Your URL
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 " \ n ";
}

function _createadditionalelements ($elements, $indentString = "") {
$ae = "";
if (Is_array ($elements)) {
foreach ($elements as $key = = $value) {
$ae. = $indentString. " < $key > $value \ n ";
}
}
return $ae;
}

function _createstylesheetreferences () {
$xml = "";
if ($this->cssstylesheet) $xml. = " Cssstylesheet. " \ "Type=\" text/css\ ">\n";
if ($this->xslstylesheet) $xml. = " 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 "
Error Creating feed file, please check write permissions.
";
}
}
}

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, "June" =>6, "Jul" =>7, "=>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) * + 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) * + 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 = " Encoding. " \ "? >\n";
$feed. = $this->_creategeneratorcomment ();
if ($this->cssstylesheet== "") {
$cssStyleSheet = "Http://www.w3.org/2000/08/w3c-synd/style.css";
}
$feed. = $this->_createstylesheetreferences ();
$feed. = "
$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. = " Syndicationurl. " \ ">\n";
$feed. = " ". Htmlspecialchars ($this->title)."\ n ";
$feed. = " ". Htmlspecialchars ($this->description). " \ n ";
$feed. = " ". $this->link. " \ n ";
if ($this->image!=null) {
$feed. = " image->url." \ "/>\n";
}
$now =new feeddate ();
$feed. = " ". Htmlspecialchars ($now->iso8601 ()). " \ n ";
$feed. = " \ n";
$feed. = " \ n";
for ($i =0; $i items); $i + +) {
$feed. = " items[$i]->link)." \ "/>\n";
}
$feed. = " \ n";
$feed. = " \ n";
$feed. = " \ n ";
if ($this->image!=null) {
$feed. = "Image->url. " \ ">\n";
$feed. = "<title>". $this->image->title."</title>\ n ";
$feed. = " ". $this->image->link."\ n ";
$feed. = " ". $this->image->url." \ n ";
$feed. = "\ n ";
}
$feed. = $this->_createadditionalelements ($this->additionalelements, "");

for ($i =0; $i Items), $i + +) {
$feed. = " items[$i]->link). " \ ">\n";
$feed. = " Posting \ n ";
$feed. = " text/html \ n ";
if ($this->items[$i]->date!=null) {
$itemDate =new feeddate ($this->items[$i]->date);
$feed. = " ". Htmlspecialchars ($itemDate->iso8601 ())." \ n ";
}
if ($this->items[$i]->source!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->source)." \ n ";
}
if ($this->items[$i]->author!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->author)." \ n ";
}
$feed. = " <title>". Htmlspecialchars (Strip_tags (STRTR ($this->items[$i]->title," \n\r "," ")))."</title>\ n ";
$feed. = " ". Htmlspecialchars ($this->items[$i]->link)."\ n ";
$feed. = " ". Htmlspecialchars ($this->items[$i]->description)." \ n ";
$feed. = $this->_createadditionalelements ($this->items[$i]->additionalelements, "");
$feed. = " \ n ";
}
$feed. = "\ 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 = " Encoding. " \ "? >\n";
$feed. = $this->_creategeneratorcomment ();
$feed. = $this->_createstylesheetreferences ();
$feed. = " Rssversion. " \ ">\n";
$feed. = " \ n ";
$feed. = " <title>". Feedcreator::itrunc (Htmlspecialchars ($this->title), 100). "</title>\ n ";
$this->descriptiontruncsize=500;
$feed. = " ". $this->getdescription ()." \ n ";
$feed. = " ". $this->link."\ n ";
$now =new feeddate ();
$feed. = " ". Htmlspecialchars ($now->rfc822 ())." \ n ";
$feed. = " ". Feedcreator_version. " \ n ";

if ($this->image!=null) {
$feed. = " \ n ";
$feed. = " ". $this->image->url." \ n ";
$feed. = " <title>". Feedcreator::itrunc (Htmlspecialchars ($this->image->title), 100). "</title>\ n ";
$feed. = " ". $this->image->link."\ n ";
if ($this->image->width!= "") {
$feed. = " ". $this->image->width." \ n ";
}
if ($this->image->height!= "") {
$feed. = " ". $this->image->height." \ n ";
}
if ($this->image->description!= "") {
$feed. = " ". $this->image->getdescription ()." \ n ";
}
$feed. = "\ n ";
}
if ($this->language!= "") {
$feed. = " ". $this->language." \ n ";
}
if ($this->copyright!= "") {
$feed. = " ". Feedcreator::itrunc (Htmlspecialchars ($this->copyright), (+). " \ n ";
}
if ($this->editor!= "") {
$feed. = " ". Feedcreator::itrunc (Htmlspecialchars ($this->editor), (+). " \ n ";
}
if ($this->webmaster!= "") {
$feed. = " ". Feedcreator::itrunc (Htmlspecialchars ($this->webmaster), (+). " \ n ";
}
if ($this->pubdate!= "") {
$pubDate =new feeddate ($this->pubdate);
$feed. = " ". Htmlspecialchars ($pubDate->rfc822 ())." \ n ";
}
if ($this->category!= "") {
$feed. = " ". Htmlspecialchars ($this->category)." \ n ";
}
if ($this->docs!= "") {
$feed. = " ". Feedcreator::itrunc (Htmlspecialchars ($this->docs). " \ n ";
}
if ($this->ttl!= "") {
$feed. = " ". Htmlspecialchars ($this->ttl)." \ n ";
}
if ($this->rating!= "") {
$feed. = " ". Feedcreator::itrunc (Htmlspecialchars ($this->rating). " \ n ";
}
if ($this->skiphours!= "") {
$feed. = " ". Htmlspecialchars ($this->skiphours)." \ n ";
}
if ($this->skipdays!= "") {
$feed. = " ". Htmlspecialchars ($this->skipdays)." \ n ";
}
$feed. = $this->_createadditionalelements ($this->additionalelements, "");

for ($i =0; $i Items), $i + +) {
$feed. = " \ n ";
$feed. = " <title>". Feedcreator::itrunc (Htmlspecialchars (strip_tags ($this->items[$i]->title)), 100). "</title>\ n ";
$feed. = " ". Htmlspecialchars ($this->items[$i]->link)."\ n ";
$feed. = " ". $this->items[$i]->getdescription ()." \ n ";

if ($this->items[$i]->author!= "") {
$feed. = "". Htmlspecialchars ($this->items[$i]->author). "\ n ";
}
/*
On hold
if ($this->items[$i]->source!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->source)."\ n ";
}
*/
if ($this->items[$i]->category!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->category)." \ n ";
}
if ($this->items[$i]->comments!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->comments)." \ n ";
}
if ($this->items[$i]->date!= "") {
$itemDate =new feeddate ($this->items[$i]->date);
$feed. = " ". Htmlspecialchars ($itemDate->rfc822 ())." \ n ";
}
if ($this->items[$i]->guid!= "") {
$feed. = " ". Htmlspecialchars ($this->items[$i]->guid)." \ n ";
}
$feed. = $this->_createadditionalelements ($this->items[$i]->additionalelements, "");
$feed. = " \ n ";
}
$feed. = " \ n ";
$feed. = " \ n ";
return $feed;
}
}

Class RSSCreator20 extends rsscreator091{

function RSSCreator20 () {
Parent::_setrssversion ("2.0");
}
}


Examples of Use:

The code is as follows:

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= "page title";
$rss->link= "URL http:/";
$rss->description= "RSS title";
while ($rowbrs =mysql_fetch_array ($brs)) {
$item =new Feeditem ();
$item->title = $rowbrs [' Subject '];
$item->link= ' http://www.jb51.net/';
$item->description = $rowbrs [' description '];
$rss->additem ($item);
}
Mysql_close ($DB);
$rss->savefeed ("RSS2.0", "Rss.xml");

I hope this article is helpful to everyone's PHP programming.

http://www.bkjia.com/PHPjc/958128.html www.bkjia.com true http://www.bkjia.com/PHPjc/958128.html techarticle how PHP generates RSS feeds This article is an example of how PHP generates RSS feeds. Share to everyone for your reference. The specific analysis is as follows: RSS (simple information aggregation, also known as aggregation content) ...

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.