• Designs Photo
  • Fantasy Photo
  • Code Photo
  • Silhouette Photo

Creative, Modern, Professional Designs

For the last 6 years, I have been creating innovative websites to capture attention and inspire the mind, balancing user experience with an attractive website interface. By the use of AJAX and CSS, websites become more interactive, and with Search Engine Optimization, they are easily found through Google, Yahoo and Bing.

Designs Photo
Fantasy Photo

Everything you see here is Original Work

Besides the jQuery library and syntax highlighting, this whole website has been created from scratch; No pre built frameworks or content management systems have been used.

This demonstrates dedication, personalization and skill, and is reflected in all of the work I produce.

Programming is a Passion

As you get to know me, you'll start to see that I've tried my hands at just about everything, ranging from the basics to the more advanced and finer points in programming.

That means you'll probably find lots of hints and tips here for many different languages, as well as anything that I find relatively interesting!

HTML Code Photo
Silhouette Photo

Inspiring Designs with Limitless Possibilities

Every website created here is a unique one, with limiting boundaries out of the questions.

Programming is always evolving and so I'm always improving my game to keep up with the changes. You'll be able to see this reflected in the high quality work that I produce.

Anuj Nair's Blog »

Creating a Custom RSS Feed using PHP and MySQL

How to create a custom RSS feed using PHP and MySQL to display the data that you want your subscribers to have quick access to at the click of a button

Posted: 25 May 2010 - Written by Anuj Nair
Many sites offer you the chance to subscribe to their site through the use of a web feed, namely RSS ( Really Simple Syndication), for quick and easy automatic updates to the sites you love. If you're a web developer who updates his site frequently and wants to offer the same service to your subscribers, you'll find that it's actually quite easy to create.

RSS : The Need-To-Know


When you check a RSS feed, you see lots of information: information about the site you're receiving the feed from, and more importantly, the blog posts which have been posted on the site. Keep all of this in mind: you'll need it when you create your own custom RSS feed.

RSS has a strict format which you need to follow in order for it to validate and work with all different RSS programs. You can use RSS Validators to check what you have coded is valid. It has a XML structure, detailing all of the different parts of the feed and is case sensitive! This is very important.

Creating your RSS Feed


I'm going to assume you already have a MySQL table setup containing all of the information you want to display in your RSS feed. It should include information such as Titles, Descriptions and Dates.

Create a new file called rss.php. We'll be tackling the problem by building our RSS feed into the variable $build, and then echoing it out into a file later.

Our first step is to define the content type as XML and that its contents will be a RSS feed:

$build = '<?xml version="1.0" encoding="ISO-8859-1" ?>
	<rss version="2.0">
		<channel>


We also open the <channel> tag. This surrounds all of our RSS content.
Next, we fill in details about the site the feed is coming from. Here is the information I am using:

<title>Blog Posts from AnujNair.com</title>
<link>http://anujnair.com/</link>
<description>The most recent blog posts from AnujNair.com</description>
<language>en-us</language>
<lastBuildDate>'.date('D, d F Y H:i:s O').'</lastBuildDate>
<managingEditor>admin@anujnair.com (Anuj Nair)</managingEditor>
<webMaster>admin@anujnair.com (Anuj Nair)</webMaster>
<copyright>Anuj Nair</copyright>'."\r\n";


Obviously, replace it with your own information. title, link, description, language and lastBuildDate are all recommended information to include. The rest are optional.

managingEditor and webMaster should be of the format Email (Full Name). This is for validation.

Now that our website information has been built, we need to build the individual blog posts information. Individual blog posts are displayed between the <item>, like so:

<item>
	<title></title>
	<guid></guid>
	<link></link>
	<description></description>
	<pubDate></pubDate>
	<author></author>
</item>


We'll use a MySQL call to fetch all of our data, and then loop through each and build the RSS feed items:

$result = mysql_query("SELECT * FROM `blog` ORDER BY `ID` DESC LIMIT 10");
while ($row = mysql_fetch_assoc($result)) {
	$build .= "\t\t\t".'<item>
		<title>'.htmlentities($row['Title']).'</title>
		<guid isPermaLink="true">http://anujnair.com/blog.php/'.$row['ID'].'/'.$row['Title'].'</guid>
		<link>http://anujnair.com/blog.php/'.$row['ID'].'/'.$row['Title'].'</link>
		<description>'.htmlentities($row['Description']).'</description>
		<pubDate>'.date('D, d M Y H:i:s O', strtotime($row['Date'])).'</pubDate>
		<author>'.$row['Email'].' ('.$row['Author'].')</author>
	</item>'."\r\n";
}


Make sure you use htmlentities to escape all characters in your title and description. Your feed won't validate if HTML entities aren't escaped properly.

pubDate is also very picky. The Date format must be as shown above, otherwise your RSS feed will not validate.

isPermaLink tells the RSS feed that the link to the blog post is permanent.

Finally, we close the channel and the RSS feed:

$build .= "\t\t".'</channel>
	</rss>';


Now we have everything in our $build variable, we're going to output it to a rss.xml file. This way, we'll be loading data from a static file everytime someone requests our RSS feed, and not from the database. If 1000's of people subscribe to our feed, and we fetch data from our database each time, we'll probably end up crippling our site! Instead, we'll choose to update a static file every day via a cron job. The final script looks like this:

<?php
	include("mysql.php");
	
	$fd = fopen("rss.xml", "wb");
	$build = '<?xml version="1.0" encoding="ISO-8859-1" ?>
	<rss version="2.0">
		<channel>
			<title>Blog Posts from AnujNair.com</title>
			<link>http://anujnair.com/</link>
			<description>The most recent blog posts from AnujNair.com</description>
			<language>en-us</language>
			<lastBuildDate>'.date('D, d F Y H:i:s O').'</lastBuildDate>
			<managingEditor>admin@anujnair.com (Anuj Nair)</managingEditor>
			<webMaster>admin@anujnair.com (Anuj Nair)</webMaster>
			<copyright>Anuj Nair</copyright>'."\r\n";
	$result = mysql_query("SELECT * FROM `blog` ORDER BY `ID` DESC LIMIT 10");
	while ($row = mysql_fetch_assoc($result)) {
		$build .= "\t\t\t".'<item>
			<title>'.htmlentities($row['Title']).'</title>
			<guid isPermaLink="true">http://anujnair.com/blog.php/'.$row['ID'].'/'.$row['Title'].'</guid>
			<link>http://anujnair.com/blog.php/'.$row['ID'].'/'.$row['Title'].'</link>
			<description>'.htmlentities($row['Description']).'</description>
			<pubDate>'.date('D, d M Y H:i:s O', strtotime($row['Date'])).'</pubDate>
			<author>admin@anujnair.com (Anuj Nair)</author>
		</item>'."\r\n";
	}
	$build .= "\t\t".'</channel>
	</rss>';
	
	fwrite($fd, $build);
	fclose($fd);

?>


Now link rss.xml on your site and setup your cron job to run this script once or twice a day.

Job done!
Tags: PHP, MySQL, RSS
Comments
Posted: 22/04/2011 at 12:03:02
Brent
Hi, I'm trying to use your script here but I want to know if there is a way to reference anchor tags (<a name="">) across the different pages? For example if I have a link on page 1 that takes me to a part of the page that has been paginated to page 3... how do youdo that?
Posted: 22/04/2011 at 13:14:04
Hi Brent,

I'm a bit confused at what you're after. Are we still talking about RSS feeds?

From what I gather, we're talking about general HTML practices; you want to be able to click on a link on Page 1, be taken to Page 3, and have the page highlight the correct part of Page 3?

If so, on Page 1, have you link like so:
<a href="example.php?page=3#someId">Go to Page 3</a>

Once clicked, this link will take you to page 3, and will center the page on whatever element has the id attribute set as "someId". For example:
<div id="someId">Some Stuff</div>


You can do the same with RSS comments. Add an ID hash tag to the end of the link, and once that link is clicked in a user's RSS reader, it will center the page on a specific element with that ID.

Is this what you're looking for?
Posted: 22/04/2011 at 16:12:45
Brent
Thanks for getting back to me so quickly, I really appreciate that.

Sorry for the confusion,I had two blogs open at the same time and I left a comment on yours by accident. I did have a question for you though, and thanks for your advice, it actually was very helpful.

My question for you is what is a cron job and how do I set it up? I am using dreamhost and they have a tab for cronjobs on their panel but I don't know how to set it up.

Thanks a million, I love your blog!
Posted: 22/04/2011 at 16:15:39
Brent
Also why is it important to run that cron job automatically twice a day?
Posted: 22/04/2011 at 17:40:16
No problem :)

A cron job is basically a process which runs a specific file (or set of commands) at a pre defined time. So in my case, I'm running a PHP file twice a day (Midday and Midnight) to update the rss.xml file I have on my server with new content.

In the case of this RSS tutorial, I'm using a PHP file to generate content and write it to a static file. I then get people to access that static file instead of a PHP file grabbing dynamic content, because if they were to access the dynamic content, it would make a request to my database every time they looked at their RSS feed, and probably cripple the db.

To set up a basic cron job, you usually just have to define the file you want to run and what time you want it to run. Your server will do the rest :)

Running it twice a day means that the RSS feed will update more often. By definition, a cron job is an automatic process.

Hope that helps!
Posted: 18/05/2011 at 13:57:37
AL
Great script and awesome explanation.

I have two questions for u, what is the exact mysql.php file structure?

And can I use the wp_posts table from the wordpress database ?

'cause I've notice in that table there are publish, auto-draft and inherit status but obviously I just want to retrieve the published ones.

will this script retrieve only the published posts or all of 'em if I use that table?

thanks in advance.
and keep up the good job !
Posted: 19/05/2011 at 02:35:01
Hi AL,

At the time, it was just a connection string to MySQL as I wasn't using classes.

So mysql_connect() and mysql_select_db()

And of course you can use a wordpress database. You'd just have to edit the SQL to select the posts from wp_posts, limiting it by where the status of the post is published.

Hope this helps
Posted: 19/05/2011 at 02:47:56
The Zend Framework also has a useful library for writing RSS feeds, building them using the DOMDocument:
http://framework.zend.com/manual/en/zend.feed.writer.html

Technically it wouldn't be a fast but potentially more flexible.
Posted: 19/05/2011 at 08:02:22
AL
thanks, it helped a lot.
Posted: 19/05/2011 at 12:47:06
AL
OK, everything seems to be working fine, I get no errors at all but the thing is that I get no content in my rss.

The database connection is working, the column names are fine and got me a little frustrated.

I even tried to use a different database, and still no content.
Posted: 19/05/2011 at 12:54:15
Firstly, make sure PHP errors and notifications are turned on, and that none are occurring.

Try dumping the variable at the end of the build, in the PHP file using die or var_dump, and seeing if there is any content in there. If not, then there is something wrong when you are building the variable.

Next run the script, and check if there is content in the rss.xml file - If not, make sure it is a writable file, you have writing permissions on the server and the file exists on the server, in the exactly place you expect it to be. In my example above, I haven't referenced the full path for the rss.xml file - you might need to change this.

If you have content in your rss.xml file (manually check by opening it in a text editor after you run your PHP script), then make sure that it contains valid XML and that your RSS reader (I use FireFox) can read it. You can check the XML is valid by searching for an XML validator and testing your output using it.

Let me know how it goes!
Posted: 19/05/2011 at 15:17:16
AL
I believe found the problem when I was validating de output xml file turned out that the little trouble makers were the ampersands (&) it appears that there's a code to display them correctly but you have to do it one by one.

Now the question is, how do I control that. Everytime it finds an ampersand it will block the rest of the content visible only in the page's source.

There's gotta be a way to automatically transform those ampersand in a way that is valid for xml format.
Posted: 19/05/2011 at 15:59:41
Did you use htmlentities on the data you grabbed from the database? This usually stops problems like this happening as it converts it all to XML and RSS friendly characters, i.e. &amp; in this case
Posted: 20/05/2011 at 00:41:40
Ok, got it working now, it turns out that the "htmlentities" function wasn't working as it should with the ampersands so I just changed that function for another one much better (except for German) that does all the job, it converts every single sign or whatever to html or xml code, it's simple, short and gets the job done. And here it is in case someone needs it:

<?php
function umlaute($text){
    $returnvalue="";
    for($i=0;$i<strlen($text);$i++){
        $teil=hexdec(rawurlencode(substr($text, $i, 1)));
        if($teil<32||$teil>1114111){
            $returnvalue.=substr($text, $i, 1);
        }else{
            $returnvalue.="&#".$teil.";";
        }
    }
    return $returnvalue;
} 
?>


Thanks again for such a good script, I found a bunch of tutorials on how to make your own rss but none of them loads data from a static file which is pretty cool if you ask me.

peace...
Posted: 30/05/2011 at 02:41:41
thomas
First off, thanks for your script! Really great job! I was just wondering, I've been running this and testing it a few times and now I seem to have a bunch of entries repeating in the reader. How do I get rid of those?

Thanks!
Posted: 30/05/2011 at 12:59:08
Hey Thomas,

There could be a couple of reasons this has happened. Firstly, make sure that you are pulling distinct entries from your SQL tables. If there are any repeat entries in there, and you aren't filtering the repeats out, they will appear multiple times.

Secondly, make sure you are overwriting the rss.xml file each time you update it. You don't want to leave old entries in there.

Let me know if that helps!
Posted: 30/05/2011 at 15:47:12
Brent
Hey Anuj, I have been having the same problem as Thomas with my feed. I have no repeating entries in my database, and i have deleted the xml file a few times since last I talked to you to try and get rid of the old posts. I have even tried making a new google account and subscribing to my blog with a different user from a different computer and it still gives me 28 items. However there are only 9 items in my databse right now. Any ideas what else could be causing this?
Posted: 31/05/2011 at 02:20:10
Hey Brent,

If you open your rss.xml file in a text editor file, do you see 9 items, or 28? If there are 28, then there is something wrong with your mysql query (you might need to modify it a bit to only pull out distinct posts).

If there are only 9 entries, then your RSS reader might be caching some results. If so, you might need to Google about specific readers to combat this.
Posted: 31/05/2011 at 11:21:03
Brent
Anuj, as always thanks for your speedy response and willingness to help. I opened the xml in a text editor and only got 9 items. I'm going to try and figure out what the deal is with the google reader and then I'll let you know what went wrong so if anyone else runs into the same error that we did (Thomas and I are friends, I referred him to your site) they will be able to fix it. Thanks again for your help mate!
Name :
Email (hidden) :
Website (optional) :
Captcha :
 
How to Post   Comment :