Using PHP to Output RFC3339 Dates from MySQL for Atom Feeds

Creating an Atom feed manually in PHP is fairly easy – it is just like generating HTML. However the Atom specification is quite strict on the date format required:

A Date construct is an element whose content MUST conform to the “date-time” production in [RFC3339]. In addition, an uppercase “T” character MUST be used to separate date and time, and an uppercase “Z” character MUST be present in the absence of a numeric time zone offset.

Unfortunately this is very different to the default date format that MySQL exports, so you need to convert it. Thankfully this is very easy. Assuming $line contains your MySQL record array then this code will work:

echo date('Y-m-d\TH:i:s\Z', strtotime($line["date_added"]));

This will output the date in the format required to pass Atom feed validation.

The only other awkward task when exporting an Atom feed is making sure that you send the correct Content-type declaration in the header. The default header Content-type for PHP output is text/html. For an Atom feed this should be application/atom+xml instead. To do this, include the following line at the top of your code, before you have output anything to the client:

header('Content-type: application/atom+xml');

Your feed should now return the correct content type, and contain dates that conform to the Atom specification.

Leave a comment

Your comment