How to create and read RSS feed for your website – PHP

RSS is formerly known as RDF Site Summary, now it stands for Really Simple Syndication. It is a form of web feed that allows other computer programs to fetch updates about the website. Programs known as RSS aggregators are created which reads the feed in XML format in a standardized way.

For example, if you are running an E-commerce site, creating an RSS feed will help visitors to view the latest products on your website. Similarly, if you are running a blog, then your RSS feed will be about the latest posts that you have published on your blog.

RSS feeds are XML files, so they must follow all the standard formats of XML. That includes the special characters, if your feed has some special characters like a single or double quote, you need to convert them to HTML entities before publishing or updating your feed.

The programs or scripts that are used to read these feeds are known as RSS aggregators. They follow a specific pattern to read and display feeds to users, so you must follow the rules and proper tags of XML to reach the global audience. There are a lot of tags which can be used in RSS but the most common are title, description, link, language, image, url, category, copyright and author.

How to create an RSS feed

There are multiple ways to create an RSS feed for your website and different people adopt different ways, that’s okay. You can either create a button on the admin panel to generate feeds and export the XML file. Then you can upload it manually using your cPanel file manager. Or you can add a function that will create or update an XML file whenever you post something new on your website. We will be using the second technique in this tutorial.

Also, you will need to create a button on your website’s main page from where users can see your feeds. One common practice is to create an anchor tag in HTML that will redirect the user to that XML file. User can then add that RSS link in this RSS aggregator software and then will automatically be notified when you upload something new on your website and your RSS feed gets updated.

The standard format of creating an RSS feed is:

<?xml version="1.0" ?>
<rss version="2.0">
    <channel>
        <title></title>
        <description></description>
        <language>en-US</language>
        <link>http://website.com/</link>

        <item>
            <title>Pont Yacht
            <description>Measures 38 inches Long.</description>
            <link>http://website.com/prod.php?id=3212</link>
        </item>
    </channel>
</rss>

You can display as many item tags as you want but the format should remain the same. So copy and paste the following code in file where you want to generate your RSS feed, typically whenever you post something new in your website.

<?php

$web_url = "http://" . $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];

$str = "<?xml version='1.0' ?>";
$str .= "<rss version='2.0'>";
	$str .= "<channel>";
		$str .= "<title>My website</title>";
		$str .= "<description>My website</description>";
		$str .= "<language>en-US</language>";
		$str .= "<link>$web_url</link>";

		$conn = mysqli_connect("localhost", "root", "", "classicmodels");
		$result = mysqli_query($conn, "SELECT * FROM products ORDER BY productCode DESC");

		while ($row = mysqli_fetch_object($result))
		{
			$str .= "<item>";
				$str .= "<title>" . htmlspecialchars($row->productName) . "</title>";
				$str .= "<description>" . htmlspecialchars($row->productDescription) . "</description>";
				$str .= "<link>" . $web_url . "/product.php?id=" . $row->productCode . "</link>";
			$str .= "</item>";
		}

	$str .= "</channel>";
$str .= "</rss>";

file_put_contents("rss.xml", $str);
echo "Done";
?>

First we are creating a variable $web_url that will hold the base URL of the website. You can just set this variable a static value, but we are trying to make it dynamic so you won’t have difficulty when moving to different domains. Then we are creating a string variable $str that will hold all the RSS feed value in string format. We will be using this variable when creating an XML file.

Channel tag will be served as a category since you might have different types of data on your website, so you can put different data in different channel tags. For example, you might have an E-commerce site and also the latest blog posts from one of your blog site.

Then we have title, description, link and url tags, they will be used to explain the properties of channel tag. The link must be your website’s main URL and language can be in one of the standard language codes. For getting website main URL we will be using PHP built-in SERVER variable and SERVER_NAME will return the name of the server which in this case will be localhost, and REQUEST_URI will return the address of folder from where this script is getting executed.

Then we are connecting with the database and fetching all the latest products in descending order (newest to oldest). You can see that we are using htmlspecialchars() function which helps to convert special characters into HTML entities. Since XML do not interpret special characters, so if you have any special characters and you are not using this function, then it might trigger an error in your RSS feed.

Finally, we are calling file_put_contents() function which will create an XML file with the content of $str variable. If the file with same name already exists, it will simply update the file and override the previous content. If you are using Linux, make sure you have folder’s write permission in order to create that file.

If you run the script now you will be able to see a file named rss.xml created in your project’s root folder. You can drag that file in your browser, and you will see the feed in proper XML format. Now the last thing you can do is to display a link in your website which when clicked will redirect the user to this page.

Link to RSS feed

We will be creating an anchor tag which when clicked will redirect the visitors to that XML file. We have also downloaded a logo of RSS from the internet, instead of text we will be placing this image inside the anchor tag. Just copy and paste the following code anywhere in your website where you want to display a link to this RSS feed:

<a href="rss.xml" target="_blank">
	<img src="feed-icon.png" style="width: 100px;">
</a>

Since we want the feed to open in a new tab so it will not disrupt the user from using the site, so we have added an attribute target=”_blank” which will tell the browser to open that link in a new tab.

6 Replies to “How to create and read RSS feed for your website – PHP”

Leave a Reply

Please disable your adblocker or whitelist this site!