Create RSS feed for a website


RSS is a good way to let third party software access your website's content and its structured metadata. Many CMS have RSS module or plugin, so if you're using one then you probably just need to enable such module on your website. However if you don't use any CMS (e.g. you make PHP website) you may want to craft RSS feed by yourself. It's quite simple.

Assume you want to add RSS feed to your website and make it accessible via URL RSS is extended from XML. Also assume you're using PHP and Twig templater. If you're not familiar with Twig, it's OK — it's so simple so you will understand everything on-the-fly.

First, let's craft the feed itself:

<?xml version="1.0" encoding="UTF-8" ?>

<rss version="2.0" xmlns:atom="">
        <title>Sam's Blog</title>
        <description>Latest posts in Sam's blog where you'll find a lot of exciting stuff.</description>
        <lastBuildDate>{{ posts[0].created }}</lastBuildDate>
        <atom:link href="" rel="self" type="application/rss+xml" />
        {% for post in posts %}
                <title>{{ post.title }}</title>
                <description>{{ post.description }}</description>
                <link>{{ }}</link>
                <guid>{{ }}</guid>
                <pubDate>{{ post.created }}</pubDate>
        {% endfor %}

Yep, that's it, this is well-crafted RSS feed template. Date fields — lastBuildDate and pubDate — should be formatted according to RFC 2822. To format a date in this format with PHP you can use:

$post->created = date(DATE_RFC2822, $post->created);

Also you should add a proper HTTP Content-Type header into the HTTP response:

header('Content-Type: application/rss+xml');

And finally, add the link to the feed into your website's <head> element:

<!DOCTYPE html>
<html lang="en">
        <!-- ... -->
        <link rel="alternate" type="application/rss+xml" title="Sam's Blog" href="" />
        <!-- ... -->
    <!-- ... -->

Done! Now your website has a well-crafted RSS feed. Don't forget to validate you feed to make sure that everything's correct:

Rate this post:
Share this page:

See also how to:

How to parse large XML files in PHP when they're too large to load them into RAM entirely
How to make POST and other types of HTTP requests and add custom HTTP headers with file_get_contents function in PHP
How to pretty print XML documents on Linux
How to run your PHP or Bash script as root in the most secure way
How to use modern MaxMind GeoIP API in PHP