RSSFeeds.com

How to Create an RSS Feed

Most websites already have a feed, or can get one with a single setting. For custom sites, a feed is about thirty lines of code. This guide covers both, with working examples in PHP, Node.js and Python.

Updated

Illustration of a developer building an RSS feed for a website

Step 1: Check Whether You Already Have One

Paste your website into the Feed Finder. If it finds a feed, skip to step 4. Most platforms create one automatically:

PlatformFeed address or setting
WordPressAutomatic at /feed/, plus feeds per category, tag, author and comments.
GhostAutomatic at /rss/.
Substack, Medium, Blogger, TumblrAutomatic; see the platform cheat sheet in the Feed Finder.
ShopifyBlogs have an Atom feed at /blogs/BLOG-HANDLE.atom.
SquarespaceAdd ?format=rss to the URL of a blog page.
WixWix Blog publishes /blog-feed.xml.
WebflowEnable the RSS feed option on a CMS collection.
DrupalThe front page feed is at /rss.xml; create others with Views.
JoomlaAdd ?format=feed&type=rss to a category or blog page.

Static Site Generators

GeneratorHow
HugoBuilt in: /index.xml for the site and every section.
JekyllThe jekyll-feed plugin creates an Atom feed at /feed.xml.
EleventyThe official @11ty/eleventy-plugin-rss plugin.
AstroThe @astrojs/rss package and an rss.xml.js endpoint.
Next.jsGenerate the XML in a route handler or at build time, for example with the feed package.
Gatsbygatsby-plugin-feed.
DocusaurusBlog feeds are built in (/blog/rss.xml and /blog/atom.xml).
Hexohexo-generator-feed.
ZolaA config option generates an Atom or RSS feed.
MkDocsmkdocs-rss-plugin.

Step 2: Make a Feed by Hand

For a small site, a landing page or a podcast with a few episodes, a static file is enough. Fill in the Feed Generator, download feed.xml and upload it to your site. Update it when you publish something new, putting the newest item at the top.

Step 3: Generate the Feed with Code

For a custom site, generate the feed from your database. The rules are the same in every language: escape text, wrap HTML in CDATA, use absolute URLs, format dates correctly, and send the right headers.

PHP

feed.php
<?php
$pdo = new PDO('mysql:host=localhost;dbname=site;charset=utf8mb4', 'user', 'secret');
$posts = $pdo->query('SELECT title, slug, summary, body, author, published_at
    FROM posts WHERE published = 1 ORDER BY published_at DESC LIMIT 20')->fetchAll(PDO::FETCH_ASSOC);

$base = 'https://example.com';
$x = fn($s) => htmlspecialchars($s, ENT_XML1 | ENT_QUOTES, 'UTF-8');
$cdata = fn($s) => '<![CDATA[' . str_replace(']]>', ']]]]><![CDATA[>', $s) . ']]>';
$last = $posts ? strtotime($posts[0]['published_at']) : time();
$lastHttp = gmdate('D, d M Y H:i:s', $last) . ' GMT';

if (($_SERVER['HTTP_IF_MODIFIED_SINCE'] ?? '') === $lastHttp) { http_response_code(304); exit; }
header('Content-Type: application/rss+xml; charset=utf-8');
header('Last-Modified: ' . $lastHttp);
header('Cache-Control: public, max-age=900');

echo '<?xml version="1.0" encoding="UTF-8"?>', "\n";
?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/">
<channel>
  <title>Example Blog</title>
  <link><?= $base ?>/</link>
  <description>Notes about the web.</description>
  <atom:link href="<?= $base ?>/feed.xml" rel="self" type="application/rss+xml" />
  <language>en</language>
  <lastBuildDate><?= date(DATE_RSS, $last) ?></lastBuildDate>
<?php foreach ($posts as $p): $url = $base . '/posts/' . rawurlencode($p['slug']); ?>
  <item>
    <title><?= $x($p['title']) ?></title>
    <link><?= $x($url) ?></link>
    <guid isPermaLink="true"><?= $x($url) ?></guid>
    <pubDate><?= date(DATE_RSS, strtotime($p['published_at'])) ?></pubDate>
    <dc:creator><?= $x($p['author']) ?></dc:creator>
    <description><?= $cdata($p['summary']) ?></description>
    <content:encoded><?= $cdata($p['body']) ?></content:encoded>
  </item>
<?php endforeach; ?>
</channel>
</rss>

Make it available at a friendly address with a rewrite rule, for example in .htaccess: RewriteRule ^feed\.xml$ feed.php [L]. Make sure nothing – not even a blank line – is output before <?xml.

Node.js (Express)

server.js
import express from 'express';

const app = express();
const esc = s => String(s).replace(/[&<>"']/g, c => ({'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&apos;'}[c]));
const cdata = s => `<![CDATA[${String(s).replaceAll(']]>', ']]]]><![CDATA[>')}]]>`;

app.get('/feed.xml', async (req, res) => {
  const posts = await db.latestPosts(20);
  const items = posts.map(p => {
    const url = `https://example.com/posts/${encodeURIComponent(p.slug)}`;
    return `
    <item>
      <title>${esc(p.title)}</title>
      <link>${esc(url)}</link>
      <guid isPermaLink="true">${esc(url)}</guid>
      <pubDate>${new Date(p.publishedAt).toUTCString()}</pubDate>
      <description>${cdata(p.summary)}</description>
    </item>`;
  }).join('');

  res.type('application/rss+xml').set('Cache-Control', 'public, max-age=900').send(`<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Example Blog</title>
    <link>https://example.com/</link>
    <description>Notes about the web.</description>
    <atom:link href="https://example.com/feed.xml" rel="self" type="application/rss+xml" />${items}
  </channel>
</rss>`);
});

Python (Flask)

app.py
from email.utils import format_datetime
from xml.sax.saxutils import escape
from flask import Flask, Response

app = Flask(__name__)

def cdata(s):
    return '<![CDATA[' + s.replace(']]>', ']]]]><![CDATA[>') + ']]>'

@app.route('/feed.xml')
def feed():
    posts = get_latest_posts(20)
    items = ''.join(f'''
    <item>
      <title>{escape(p.title)}</title>
      <link>https://example.com/posts/{p.slug}</link>
      <guid isPermaLink="true">https://example.com/posts/{p.slug}</guid>
      <pubDate>{format_datetime(p.published_at)}</pubDate>
      <description>{cdata(p.summary)}</description>
    </item>''' for p in posts)
    xml = f'''<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Example Blog</title>
    <link>https://example.com/</link>
    <description>Notes about the web.</description>
    <atom:link href="https://example.com/feed.xml" rel="self" type="application/rss+xml" />{items}
  </channel>
</rss>'''
    return Response(xml, mimetype='application/rss+xml')

format_datetime needs a time-zone-aware datetime to produce a correct offset. Prefer a library? Use feedgen in Python, feed in Node.js, or laminas-feed in PHP.

Step 4: Announce the Feed

Diagram of RSS autodiscovery: a link rel alternate tag in the HTML head tells feed readers where the feed is
Autodiscovery: the page head points readers to the feed.

Add autodiscovery tags to the <head> of every page, so readers and browser extensions find the feed when someone pastes your site address:

<link rel="alternate" type="application/rss+xml" title="Example Blog" href="https://example.com/feed.xml">
<link rel="alternate" type="application/atom+xml" title="Example Blog (Atom)" href="https://example.com/atom.xml">
<link rel="alternate" type="application/feed+json" title="Example Blog (JSON)" href="https://example.com/feed.json">

Also link to it visibly – a "Subscribe via RSS" link in the footer or next to your newsletter form helps people who don't know they can paste a site address into a reader.

Step 5: Validate and Test

  1. Run the feed through the Feed Validator and fix every error.
  2. Open it in the Feed Viewer to see how readers will display it.
  3. Subscribe in two different readers and publish a test post to see it arrive.

Then read the best practices to make it fast, reliable and friendly to every reader.

Sources and Further Reading