Create RSS feed with PHP

In this tutorial we shall be looking how to make an RSS feed using php & xml for the bookmark application.

1) First create the below

<?php # script 0.5 - bmarks_rss.php

2) Then we need to send the content-type header

// This will create an RSS feed.

header('Content-type: text/xml');

This page will have a .php extension as it’s a php page that must be handled correctly by the Web server.

3) Create the initial RSS code:

echo '<?xml version="1.0"?>
<rss version="2.0" xmlns:atom="">
<atom:link href="" rel="self" type="application/rss+xml" />
<title>Bookmarks by Basshead</title>
<description>New bookmarks added by Basshead!!</description>

4) Connect to the database

require_once ('../mysqli_connect_bm.php');

This may be different depending how you have set-up your database connection.

5)Define the query

$q = "SELECT bmarks_id, bname, baddy, bmdesc, added_date
FROM b_marks
ORDER BY b_marks.added_date DESC
LIMIT 50";

You must have date column within your b_marks table, if you do not have one then please create one before moving on. Again this query may change if your database structure is different.

6) Retrieve the results

$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQL_NUM)) {

7) Print each record

echo '<item>
<title>' . htmlentities($row[1]) . '</title>
<description>' . htmlentities($row[3]) . '</description>
<link>' . $row[2] . '</link>
<guid>' . $row[2] . '</guid>
<pubDate>' . date('r', strtotime ($row[4])) . '</pubDate>

} // End of while loop

This is the most important part of the script. The title is the bookmark name, then the description which is run through the htmlentities() function as xml does not allow many characters that may appear. Next is the link to the bookmark URL then guid which is not required but a good idea as it’s a unique identifier for each item.
Finally the pubDate which needs to be an exact format, but using php date() function and the :r makes a shortcut to the process. I have also added strtotime to help with the date format. This was a problem area for me so you may not need that.

8 ) Last but by no means least complete the channel and rss element

// complete channel and rss element

echo '</channel>


Then test it out in an application that supports RSS feeds.

Leave a Reply

Your email address will not be published. Required fields are marked *

To submit your comment, click the image below where it asks you to...
Clickcha - The One-Click Captcha