How do I create RSS feeds?

The <cffeed> tag can be used to both read and create RSS feeds. To create an RSS feed, you need two things. First you need the data that will provide the content for RSS feed. Next you need a set of properties that define the RSS feed. Let's begin by getting the data for the feed. <cffeed> supports generating a feed from a query or structure. Most people will want to use a query, so let's begin with that:

<cfquery name="entries" datasource="blogdev" maxrows="10">
select   *
from   tblblogentries
</cfquery>

Now that we have the data, we need to create a structure that define the properties for the RSS feed. The most important part of the structure is the type of RSS feed we are creating. ColdFusion supports creating two types of RSS feeds: RSS 2 and Atom 1. To create an RSS 2 feed you would do:

<cfset p = structNew()>
<cfset p.version = "rss_2.0">

Both RSS 2 and Atom 1 have required and optional properties you can use. For RSS 2, the minimum required properties you must use are title, link, and description. Here is a full example:

<cfset p = structNew()>
<cfset p.version = "rss_2.0">
<cfset p.title = "My Feed">
<cfset p.link = "http://www.linktomysite.com">
<cfset p.description = "About my site...">

Obviously the value you use for these properties will depend on your site and the RSS feed you are creating.

The last step is to pass both the properties and data to the <cffeed> tag. You can generate either a file or an XML variable. In this example we will create the XML and output it:

<cffeed action="create" query="#entries#" xmlVar="rss" properties="#p#">
<cfcontent type="text/xml" reset="true"><cfoutput>#rss#</cfoutput>

By default, ColdFusion looks at the query for columns with particular names. So for example, in RSS 2 the body of each item in the feed maps to a column named content. If your query columns don't match up with what RSS 2 (or Atom 1) is looking for, you can provide a set of aliases using the columnMap structure. Define a new structure where each key represents a column in RSS 2 and each value represents a column in your data.

<cfset c = structNew()>
<cfset c.content = "body">
<cfset c.publisheddate = "posted">

This code tells ColdFusion to map the body column in the query to the content field in the RSS feed. It also tells ColdFusion to map the posted column to the publisheddate field. Once you have this structure you can pass it to the <cffeed> tag:

<cffeed action="create" query="#entries#" xmlVar="rss" properties="#p#" columnMap="#c#">

This question was written by Raymond Camden
It was last updated on December 20, 2008.

Categories

Strings

Comments

comments powered by Disqus