atom feed using xml and xslt
I friend of mine asked if he could get a feed of sodnpoo. As the site was really just a lump of html and some css that wasn't really possible. I decided I'd really like to have a go at properly separating raw post data from the form and function. I'd also been wanting to have a look at xslt.
I started by splitting the posts in to separate xml files and applying an xsl(t) file using the <?xml-stylesheet ...>. Here's the xml for the birthday cake post:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="/sodnpoo.xsl"?>
<xml>
<post>
<title>birthday cake</title>
<date>
22 Dec 2007
</date>
<p>
It was my birthday the other day. Here's the fantastic cake Vicky (my girlfriend) made for me:
</p>
<image src="/birthdaycake.png"/>
</post>
</xml>
This is then processed by the xslt on the client to transform the xml into html. This is a small snippet of the .xsl file showing how it transforms the title tag in the xml to a span with both the href and the value inside the tag using the value from title.
<xsl:template match="title">
<span class="header">
<a href="/posts.xml/{.}.xml">
<xsl:value-of select="."/>
</a>
</span>
</xsl:template>
With the conversion to xml and the xslt in place the individual posts were working well. I put together a short php script to build a front page displaying all posts in reverse date order. The script reads in the contents of the posts directory then uses DOM to extract and sort by the date, then staples them all back together and adds the xml-stylesheet tag used in the singles posts. The same xslt works on both the individual and the list of posts because it transforms all entities called 'post'. It's just the individual posts only have one.
Next I started thinking about the feed itself. After researching rss I found out there's a handful of different formats that you can use for your feed. I like standards so I decided to use atom . It's the only one that is IETF approved.
Now I just had to write an xslt to transform the same data that had been assembled by the front page script into an atom feed, but this time the transfomation needs to be done server side, using php's built in functions. XSLT works so well I was able to put a switch in the script so it used the html xslt instead, producing the front page html server side too with no modifications.
To finish off I added <link rel="alternate" type="application/atom+xml" title="sodnpoo.com feed" href="/?x=atom" /> to the top of the html xslt so you should get an rss icon to easy subscribe.