Pete Freitag Pete Freitag

Parsing RSS with CFMX

Published on September 12, 2003
By Pete Freitag
coldfusion

I came up with a code sample to parse RSS with CFMX today based on a question about CFMX XML functions on my local CFUG mailing list. It should do ok with RSS 2.0, and 0.91, and also well formed RSS 0.92. It won't work with RSS 1.0.

<cfhttp url="https://www.example.com/newsrss.cfm" method="get" />
<cfset rss = XMLParse(cfhttp.filecontent)>

<!--- get an array of items --->
<cfset items = XMLSearch(rss, "/rss/channel/item")>
<cfdump var="#items#">
<cfset rssItems = QueryNew("title,description,link")>

<!--- loop through the array of items --->
<cfloop from="1" to="#ArrayLen(items)#" index="i">
  <cfset row = QueryAddRow(rssItems)>
  <cfset title = XMLSearch(rss, "/rss/channel/item[#i#]/title")>
  <cfif ArrayLen(title)>
    <cfset title = title[1].xmlText>
  <cfelse>
    <cfset title="">
  </cfif>
  <cfset description = XMLSearch(items[i], "/rss/channel/item[#i#]/description")>
  <cfif ArrayLen(description)>
    <cfset description = description[1].xmlText>
  <cfelse>
    <cfset description="">
  </cfif>
  <cfset link = XMLSearch(items[i], "/rss/channel/item[#i#]/link")>
  <cfif ArrayLen(link)>
    <cfset link = link[1].xmlText>
  <cfelse>
    <cfset link="">
  </cfif>
  <!--- add to query --->
  <cfset QuerySetCell(rssItems, "title", title, row)>
  <cfset QuerySetCell(rssItems, "description", description, row)>
  <cfset QuerySetCell(rssItems, "link", link, row)>
</cfloop>

<ul>
<cfoutput query="rssItems">
  <li><a href="#rssItems.link#">#rssItems.title#</a> - #rssItems.description#</li>
</cfoutput>
</ul>




rss cfml xml

Parsing RSS with CFMX was first published on September 12, 2003.

If you like reading about rss, cfml, or xml then you might also like:

Fixinator

The Fixinator Code Security Scanner for ColdFusion & CFML is an easy to use security tool that every CF developer can use. It can also easily integrate into CI for automatic scanning on every commit.


Try Fixinator

CFBreak
The weekly newsletter for the CFML Community


Comments

Out of curiosity (an please realize I just recently started working with RSS). Why don't you just use XSLT transformations to merely format the RSS as you see fit? Or are you trying to convert it for storage purposes? I am not sure of the benefits (execution time, etc.) of doing either, but I found in my recent work on a CF based Aggregator that XSLT was the easiest to do. The reason for this is that I wanted to be able to change the layout depending on the feed if necessary. Of course it defaults to a generic layout that will handle all forms of RSS.
by Frank on 11/16/2005 at 9:36:41 AM UTC