PHPRO.ORG

Format Date For RSS Feed

Format Date For RSS Feed

Here is a small function that makes use of the PHP date function to return a date string formatted for use with RSS feeds. The RSS feed pubDate is optional when when creating RSS feeds, however, some agtregators complain bitterly when it is missing. As an aside, it is nice to know when an RSS item was published for ease of reading.

The RSS publication date takes the form of Mon, 02 Jul 2009 11:36:45 +0000 and with the PHP date function, it is just a simple matter of putting in the correct formatting. In PHP 5.1.0 date constants were added to do all this work for the user and is now even easier and less code.

Previously to format a date the formating would look like this:


<?php
        date
('D, d M Y g:i:s O'$timestamp);
?>

With the addition of the date constants, the formatting is now much simpler and provides and internal mapping of the formatting string.


<?php

    
/**
     *
     * @generate RSS formated date 
     *
     * @param int $timestamp The UNIX_TIMESTAMP
     *
     * @return string
     *
     */
    
function rssDate($timestamp=null)
    {
        
/*** set the timestamp ***/
        
$timestamp = ($timestamp==null) ? time() : $timestamp;

        
/*** Mon, 02 Jul 2009 11:36:45 +0000 ***/
        
return date(DATE_RSS$timestamp);
    }
?>

Example Code


<?php

        
/*** with no specified date ***/
        
echo rssDate();

        echo 
'<br />';

        
/*** with specified date ***/
        
echo rssDate(1110867488);
?>

Demonstration

Fri, 14 Dec 2018 20:45:40 -0800
Mon, 14 Mar 2005 22:18:08 -0800