Create RSS feed for a website

4

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 samblog.com website and make it accessible via URL https://samblog.com/news.rss. 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="http://www.w3.org/2005/Atom">
    <channel>
        <title>Sam's Blog</title>
        <description>Latest posts in Sam's blog where you'll find a lot of exciting stuff.</description>
        <link>https://samblog.com</link>
        <generator>samblog.com</generator>
        <language>en-us</language>
        <lastBuildDate>{{ posts[0].created }}</lastBuildDate>
        <atom:link href="https://samblog.com/news.rss" rel="self" type="application/rss+xml" />
        {% for post in posts %}
            <item>
                <title>{{ post.title }}</title>
                <description>{{ post.description }}</description>
                <link>{{ post.link }}</link>
                <guid>{{ post.link }}</guid>
                <pubDate>{{ post.created }}</pubDate>
            </item>
        {% endfor %}
    </channel>
</rss>

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">
    <head>
        <!-- ... -->
        <link rel="alternate" type="application/rss+xml" title="Sam's Blog" href="https://samblog.com/news.rss" />
        <!-- ... -->
    </head>
    <!-- ... -->
</html>

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

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