Creating an RSS Feed Using PHP and PDO

Using an RSS feed on your website is a great way of letting your visitors, search engines or directories, get a hand on your content. RSS feeds are common practice on most blogs and CMS platforms including WordPress, Joomla and evenly the newly released Ghost. If you’re using a CMS or similar platform, the likelihood is that you won’t need to implement an RSS feed yourself.

So when might you want to add an RSS feed manually? Let’s take the example of a developer who has put together a bespoke web software application, their own CMS or potentially, you’ve put together a little blog/news section for a client you may have. You may want to add the ability to publish your content to a variety of directories or news and feed websites. Well now, it’s simple. Below you’ve got the step-by-step process to create anything from the simple, standard-compliant RSS feed – up to the more advanced.

How to Create an RSS Feed Using PHP and PDO

The additional tags that will be covered in this article include the category and image elements. Both of which can be expanded on to provide an RSS feed dedicated to sorting data into specific categories; you could take the guid element and match a unique ID to a given collection of categories. Or similar, you may have a photo-focused website, perhaps an image sharing tool? You can bunch your image tags together and send them over in an RSS feed allowing others to subscribe easily to your updates!

What is an RSS Feed?

RSS stands for ‘Really Simply Syndication’ and it is the family of web formats to publish frequently updated content. An RSS feed can then be read by a feed reading software or by another website that may wish to display the content of your feed.

An RSS document is built using XML and implements a handful of standardised tags that allow us to output certain information about our content. This is a little snippet from the RSS feed from my site at ALJT Media:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
<channel>
	<title>ALJT Media</title>
	<link>http://www.aljtmedia.com/</link>
	<atom:link href="http://www.aljtmedia.com/blog/feed/" rel="self" type="application/rss+xml"/>
	<description>Latest blog articles from ALJT Media</description>
	<language>en-gb</language>
	<item>
		<guid>http://www.aljtmedia.com/blog/so-what-is-pantone</guid>
		<title><![CDATA[ So, What Is Pantone? ]]></title>
		<description><![CDATA[If you don&amp;#039;t know already, you should. Pantone&amp;nbsp;is&amp;nbsp;the&amp;nbsp;way for designers to communicate printed colour. It is the standard language for colour communication from designer to manufacturer to retailer to customer.]]></description>
		<link>http://www.aljtmedia.com/blog/so-what-is-pantone</link>
		<dc:creator>Adam Churcher</dc:creator>
		<pubDate>Sun, 03 Nov 2013 08:36:48 -0500</pubDate>
		<category><![CDATA[ Colour ]]></category>
		<category><![CDATA[ Design ]]></category>
		<category><![CDATA[ Pantone ]]></category>
		<category><![CDATA[ Print ]]></category>
	</item>
</channel>
</rss>

With search engines and the likes of Google and Yahoo pushing and driving forward the focus on unique content, an RSS feed is a great way to distribute and allow others to easily get hold of your content. We’ll be looking into implementing the Dublin Core tags and additional tags you can implement to provide search engines with more of a ‘structured data’ feel to your content.

Creating Your RSS Feed

To create an XML file, we have to dynamically loop through the data we want to display and output our XML tags. To do this, we’re going to focus on implementing unique search engine optimized tags into our RSS feed, however you’re able to take advantage of free PHP RSS feed writer classes that are widely available.

In this example, we’re going to assume the very simple database schema and that we have setup a database connection using the PDO class (it’s very easy to recreate the example in MySQL, but I’d highly recommend using a non-deprecated SQL class).

/**
 * Setup our database instance.
 * Full details on why you should be using PDO: http://aljt.in/3j
*/
try {  

	# MS SQL Server and Sybase with PDO_DBLIB  
	$DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");  
	$DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass"); 
  
	# MySQL with PDO_MYSQL  
	$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);  
  
	# SQLite Database  
	$DBH = new PDO("sqlite:my/database/path/database.db");  
	
}
catch(PDOException $e) {  
	echo $e->getMessage();  
}

# Create the RSS feed
$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title>Your RSS feed Title</title>
		<link>http://www.example.com</link>
		<description>This is an example RSS feed</description>
		<language>en-gb</language>
		<copyright>Copyright (C) 2013 example.com</copyright>';

# Let's query our data
$statement = $DBH->prepare("SELECT * FROM data ORDER BY date DESC");
$statement->execute();
$statement->setFetchMode(PDO::FETCH_ASSOC);

# Check we've got some results
if($statement->rowCount() > 0) {

	# Loop over the rows
	while($row = $statement->fetch()) {

		$rssfeed .= '<item>
			<title>'.$row['title'].'</title>
			<description>'.$row['description'].'</description>
			<link>'.$row['link'].'</link>
			<pubDate>'.date("D, d M Y H:i:s O", strtotime($row['date'])).'</pubDate>
		</item>';
		
	}

}

# Close RSS feed
$rssfeed .= '
	</channel>
</rss>';

In the code above, we’re fetching the information required from our table using the PDO execute option. We set the ‘fetch mode’ as an associate array so we can map our column names on each row to their values. The example will use a simple while loop that’ll keep checking if we have any more data to output. The query can be adjusted to display the latest 15, 30, etc.. records by altering the SQL query.

Implementing Dublin Core

Dublin Core is a widely used Ontology that allows us to express more information about the content we’re outputting. To begin, we need to add some XML namespaces to our XML tag. This lets the XML document know what information we’re describing by using the consequent namespace schema. The schema will specify the data type, format, accepted values, range constrains, etc.

Our new code will look like this:

# Create the RSS feed
$rssfeed = '<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" 
	xmlns:atom="http://www.w3.org/2005/Atom" 
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:dc="http://purl.org/dc/elements/1.1/">
	<channel>
	<title>ALJT Media</title>
	<link>http://www.aljtmedia.com/</link>
	<atom:link href="http://www.aljtmedia.com/blog/feed/" rel="self" type="application/rss+xml" />
	<description>Latest blog articles from ALJT Media</description>
	<language>en-gb</language>
	<copyright>Copyright (C) 2013 aljtmedia.com</copyright>';

Now we want to adjust the loop section. In this, we’ll be adding the encoded tag from the content schema (content:encoded) this allows us to output the entirety of the content data. We can use this to append ‘ShareThis’ or ‘AddThis’ buttons so that RSS feed readers will pick up and display the icons to share the content. Additionally, we’re going to add creator information from the Dublin Core ontology, this will allow search engines to identify the resource owner.

$rssfeed .= '<item>
	<title>'.$row['title'].'</title>
	<description>'.$row['description'].'</description>
	<guid isPermaLink="true">'.$row['link'].'</guid>			
	<link>'.$row['link'].'</link>
	<pubDate>'.date("D, d M Y H:i:s O", strtotime($row['date'])).'</pubDate>
	<content:encoded><![CDATA['.html_entity_decode($row['content'], ENT_QUOTES, 'utf-8').']]></content:encoded>
	<dc:creator>'.$v['author'].'</dc:creator>
</item>';

Adding Image and Category Information

We’ve now got some understanding of what the content is about through the description and encoded content. We’re also going say who the creator and author of the content is. But how do we associate the data with an image, say a featured thumbnail or article image? And how do we assign the data to particular categories?

For the categories, I’m working off the assumption that categories will be stored as a comma separated value (for ease of simplicity) though you’re able to normalize the data in your database schema and take advantage of the group and concatenation functions available in SQL.

$rssfeed .= '<item>
	<title>'.$row['title'].'</title>
	<description>'.$row['description'].'</description>	
	<guid isPermaLink="true">'.$row['link'].'</guid>		
	<link>'.$row['link'].'</link>
	<pubDate>'.date("D, d M Y H:i:s O", strtotime($row['date'])).'</pubDate>
	<content:encoded><![CDATA['.html_entity_decode($row['content'], ENT_QUOTES, 'utf-8').']]></content:encoded>
	<dc:creator>'.$v['author'].'</dc:creator>
	<image>
		<link>'.$row['link'].'</link>
		<url>'.$row['image_source'].'</url>
		<title><![CDATA['.html_entity_decode($row['image_title'], ENT_QUOTES, 'utf-8').']]></title>				
		<description>'.$row['image_caption'].'</description>
		<height>'.$row['image_height'].'</height>
		<width>'.$row['image_width'].'</width>
	</image>';
	
	# Get our categories
	# Assuming: RSS,Feed,Example,PHP
	if(!empty($row['categories'])) {
		
		$categories = explode(',', $row['categories']);
		
		if(!empty($categories)) {
			foreach($categories as $tag) {
				$rssfeed .= '<category>'.$tag.'</category>';	
			}
		}				
	}
	
$rssfeed .= '</item>';

Now you’ve got your media, category, author and content details pulled in – success!

Linking to your RSS Feed

Once you’ve saved, setup and tested your feed you’re able to easily link to it from within your HTML head. Simply add this one line of code: (we’re assuming you’ve made a directory called feed and saved it as index.php)

<link rel="alternate" href="/feed/" title="RSS feed" type="application/rss+xml" />

Hopefully you’ve now got your own RSS feed setup and working correctly.

If you’ve found this tutorial helpful, please comment below or give us a thumbs up and share the link onwards and upwards.

Author: (1 Posts)

Lewis is the managing director of the Cheshire based Web Design company, ALJT Media. He has a keen interest in blogging, design, development, social media and technology, and is an active web and iOS developer.

Comments