One JSON shape for RSS, Atom and RDF feeds
Three feed formats that can’t agree where their items live come out of RSS to JSON as one predictable array.
A feed can be RSS 0.9x or 2.0, RSS 1.0 (which is RDF), or Atom, and any of them can carry extra namespaces such as Media RSS and Dublin Core. My RSS to JSON reads any of them and gives back one array with the same shape, ready for json_encode().
A few fixed rules
I kept the output to a handful of rules that the reading code can count on:
- the result is always
['channel' => [...]], Atom included - items are always a list under
channel['item'] - an element with only text becomes a string, and repeated elements become a list
- attributes go under
@attributes, and text next to attributes or child elements under@value - prefixed elements keep their prefix, such as
media:thumbnailordc:creator
Nearly all of it is one recursive method, parseElement() in src/RSSToJson.php. It collects every child into a list under its name, then unwraps the lists that hold only one entry:
// Flatten single-child arrays
foreach ($data as $key => $val) {
if (count($val) === 1 && array_key_exists(0, $val)) {
$data[$key] = $val[0];
}
}
// Add text content if element has no children
$text = trim((string)$element);
if (empty($data) && $text !== '') {
return $text;
} elseif ($text !== '') {
$data['@value'] = $text;
}
The array_key_exists(0, $val) check is what keeps @attributes intact. An element with one attribute has an @attributes map with one entry, keyed by the attribute’s name. There’s no key 0, and the map stays a map.
Where the items are
The three formats don’t agree on where the items live. RSS 2.0 puts <item> inside <channel>. RSS 1.0 puts its items beside the channel, directly under the root. Atom has no channel element at all, and calls its items <entry>. parseXml() looks in each place in turn:
// RSS 0.9x/2.0 keep items inside <channel>, RSS 1.0 (RDF) puts them
// beside it under the root, and Atom calls them <entry>.
$items = $channel->item ?? $xml->item ?? $xml->entry ?? [];
The items are parsed separately and always written as a list, even when there’s only one. A feed with no items gets an empty list, so channel['item'] is always there. For Atom, the root <feed> element stands in for the channel. Its entries end up in two places: under entry, where the general parser put them, and under item. Read item. The entry key follows the general rule, and in a feed with a single entry it holds an object.
Default namespaces and shared prefixes
Atom declares its namespace as the default one: <feed xmlns="http://www.w3.org/2005/Atom">, and SimpleXML’s getNamespaces(true) lists it with an empty prefix. Reading children for that empty prefix as well as the unprefixed ones would give every element twice, as :title and title, so the parser skips the empty prefix. RSS 1.0 declares a default namespace too.
Prefixed children are matched by namespace URI, because FeedBurner’s RSS 2.0 feeds bind the Atom namespace to two prefixes: atom: on the self link, and atom10:, declared on the element itself, on the hub link. The test fixture copies the pattern:
<atom:link href="https://example.com/feed.xml" rel="self" type="application/rss+xml"/>
<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="https://pubsubhubbub.appspot.com/"/>
Matched by URI, atom:link and atom10:link each list both links. The one exception is a prefix bound to the same URI as the default namespace, which matches on the prefix, because matching it by URI would read every unprefixed element a second time:
$defaultUri = $namespaces[''] ?? null;
foreach ($namespaces as $prefix => $uri) {
$prefix = (string) $prefix;
if ($prefix === '') {
continue;
}
$children = $uri === $defaultUri ? $element->children($prefix, true) : $element->children($uri);
foreach ($children as $childName => $child) {
$qualifiedName = $prefix . ':' . $childName;
$data[$qualifiedName][] = $this->parseElement($child, $namespaces);
}
}
Each format has its own test fixture, and so do these namespace cases. feedburner.xml checks that atom:link and atom10:link both hold both links. atom-prefixed.xml declares the Atom namespace as the default and again as atom:, writes one element with the prefix, and the test checks that the keys come out exactly as atom:subtitle, title, id, entry and item. The RSS 1.0 test checks for stray colons, and another test covers CDATA, which comes back literal.
Text, entities and CDATA
Plenty of feeds aren’t quite valid XML, so the text is cleaned up before libxml sees it. A UTF-8 byte order mark and any whitespace before the XML declaration are removed, because the declaration has to come first. UTF-16 documents are left alone, since libxml reads their byte order mark to pick the encoding. Then any & that doesn’t start one of XML’s own entities is escaped, outside CDATA sections:
$escaped = preg_replace('/&(?!amp;|lt;|gt;|quot;|apos;|#[0-9]+;|#x[0-9a-fA-F]+;)/', '&', $text);
“Fish & chips” parses, and an HTML entity XML doesn’t define, such as , comes back as the literal text rather than failing the whole feed. Numeric references such as © still decode. CDATA is loaded as plain text, and whatever is inside it stays literal: an & inside CDATA comes back as &.
The odd cases it leaves alone
I left a few things the way the rules make them. Only items are guaranteed to be a list. An item with one category has a string under category, and an item with two has a list. Code reading anything that can repeat has to handle both.
An empty element such as <title></title> comes back as an empty array, which json_encode() writes as [].
HTML that a feed forgets to escape or wrap in CDATA is XML as far as the parser can tell. A description of Hello <b>bold</b> world comes back as {"b": "bold", "@value": "Hello world"}, with the bold word moved out and two spaces where it was. Feeds are supposed to escape their HTML, and most do.
From the command line or PHP
composer require tomgould/rsstojson
vendor/bin/rsstojson https://example.com/feed.xml
The command prints the feed as pretty-printed JSON, or the reason it failed. From PHP:
use TomGould\RSSToJson\RSSToJson;
$parser = new RSSToJson();
$feed = $parser->parseUrl('https://example.com/feed.xml');
if ($feed === null) {
echo $parser->getLastError(), PHP_EOL;
} else {
echo count($feed['channel']['item']), ' items', PHP_EOL;
}
parseFile() and parseString() do the same for a local file or a string, through the same clean-up. Fetching a feed from an address a visitor typed takes more care, and Fetching a feed from a URL you don’t trust covers it.
More on RSS to JSON
Featured projects
-
Apple News API
Publish articles and live coverage to Apple News from PHP, with the whole Apple News Format built from objects.
-
GitHub Auditor
Health, access and activity reports for more GitHub and Bitbucket repositories than you can keep in your head.
-
PrintMD
Markdown in, and a designed PDF, Word or PowerPoint file out. Its PDF service runs on your own computer.
-
Where Should I Live
Which city would leave you best off? Cities ranked by take-home pay, living costs, visas and the way you live.
-
Solar Calendar
Thirteen months of exactly four weeks, with the year starting on the first Monday on or after the spring equinox.
More writing
-
Many sessions at once, and what still needs me
Fifteen coding-agent sessions across two Linux boxes, one session that watches the rest, what it may answer for me, what it never may, and why a yes it passes on gets checked against what I typed.
-
61 public repos of agent tooling, none installed, six ideas kept
One author, 61 public repositories of coding-agent tooling: what I checked before any of it got near my Linux boxes, why none of it was installed, and the six ideas I built my own way.
-
Rules a coding agent cannot talk its way round
The hook that reads every command a coding agent wants to run on my Linux boxes: what it refuses, the 27 proofs that its tests fail when a rule is taken out, and the four lines every report opens with.
-
Dozens of repos, one person
46 repositories and two Linux boxes with nobody else on them: the diary, the decision table, the rebuild guide and the job that keeps both sets of clones in step.