Create RSS Feed in PHP | andi setiawan's blog

This is the easiest way to build a RSS feed in PHP. Because we don’t have to modify the feed file (feed.xml, or another xml file) anymore every we adding more content into the site.. And here’s the key concept:

Every the PHP file executed, the PHP file will output XML-based data to the browser by modifiying the PHP’s header.

In order to output a XML-based data by PHP, you will need to put this line into the PHP script:

header(‘Content-Type: text/xml; charset=UTF-8’, true);

the line above will send an xml file to your browser with XML format.

Now you will need to fill in the XML with RSS-formatted data, so the reader can read their RSS feed.

Below is the basic RSS format, you need some scripting basic to give the data into the XML.

<?xml version=”1.0″ encoding=”UTF-8″ ?>

<rss version=”2.0″
xmlns:content=”http://purl.org/rss/1.0/modules/content/”
xmlns:wfw=”http://wellformedweb.org/CommentAPI/”
xmlns:dc=”http://purl.org/dc/elements/1.1/”
xmlns:atom=”http://www.w3.org/2005/Atom”
xmlns:sy=”http://purl.org/rss/1.0/modules/syndication/”
>

<channel>
<title><? echo $sitename;?> RSS2 feed</title>
<atom:link href=”<? echo $sitepath;?>rss.php” rel=”self” type=”application/rss+xml” />
<link><? echo $sitepath;?>feed</link>
<description><? echo $desc;?></description>
<pubDate><?php echo mysql2date(‘D, d M Y H:i:s +0000’, $latest_post_date, false); ?></pubDate>
<generator>rss2</generator>
<language>en-us</language>
<sy:updatePeriod>hourly</sy:updatePeriod>
<sy:updateFrequency>1</sy:updateFrequency>
<?
$search = “SELECT * FROM $data_table order by id desc limit 10“;
$query = mysql_query($search);
while ($content = mysql_fetch_array($query))
{
?>
<item>
<title><?=$content[title]?></title>
<link><?=$sitepath.$content[url];?></link>
<comments><?$sitepath.$content[url].”#comm”; ?></comments>
<pubDate><?php echo mysql2date(‘D, d M Y H:i:s +0000’, $content[waktu], false); ?></pubDate>
<dc:creator><?=$content[user]?></dc:creator>
<guid isPermaLink=”false”><?=$sitepath.$content[url];?></guid>
<description><![CDATA[<?=$content[pembuka]; ?>]]></description>
<content:encoded><![CDATA[<?=$content[pembuka]; ?>]]></content:encoded>
<wfw:commentRss><?=$sitepath.”feed/comment/”;?></wfw:commentRss>
</item>
<? } ?>
</channel>
</rss>

The number of feed is depend on how many <item> tag that exist in the XML file.. You may find the bolded words “limit 10” in the line above, that will cause the PHP will only call the latest 10 data and put it into ten <item> tags.

If there are some error in parsing or reading, you may validate the RSS feed at this address: http://validator.w3.org/feed/


Posted in programming, Tips n Trik |

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: