feed-io 3 : JSON Feed support

In my previous post I introduced JSON Feed, a new syndication standard published on May 17, 2017.

And now feed-io supports this new format since the last release. It was tagged 3.0 as it breaks compatibility with the previous version, which was a necessary evil because FeedIo::format() returned a DomDocument, no longer relevant. Now this method returns a string you can display without calling saveXML() anymore. This is the main change from 2.x to 3.0 and if you need to know everything on how to upgrade your code, please refer to the upgrade guide.

For those how don’t know feed-io yet, it is a PHP library built to read and write feeds initially written with RSS and Atom formats in mind. I sometimes had the feeling that one day a JSON standard will come this way, but I always ended thinking “nay, not that year”. Good news : I’m finally wrong ! And I guess nobody cares about what I am thinking, so now I’ll get to the point : the code.

Want to read a JSON feed ? It’s easy, it works like with the other formats :

$feedIo = \FeedIo\Factory::create()->getFeedIo();

$feed = $feedIo->read('https://jsonfeed.org/feed.json')->getFeed();

foreach( $feed as $item ) {
// here we access $item's properties
}

Try it with https://jsonfeed.org/xml/rss.xml instead of the JSON resource. $feed will contain exactly the same properties with the same items.

Now we can use feed-io to format a feed in multiple formats :


use \FeedIo\Factory;
use \FeedIo\Feed;

$feed = new Feed();
$feed->setLink('https://feed-io.net');
$feed->setTitle('feed-io example feed');

// The item instance SHOULD be instanciated by the feed
$item = $feed->newItem();

$item->setTitle('a title');
$item->setLastModified(new \DateTime());
$item->setLink('https://feed-io.net/item/1');
$item->setDescription('Hope you like the code you are reading');

$feed->add($item);

$feedIo = Factory::create()->getFeedIo();

echo 'ATOM' . PHP_EOL;
echo $feedIo->format($feed, 'atom');
echo PHP_EOL;

echo 'RSS' . PHP_EOL;
echo $feedIo->format($feed, 'rss');
echo PHP_EOL;

echo 'JSON Feed' . PHP_EOL;
echo $feedIo->format($feed, 'json');
echo PHP_EOL;

I used the same objects ($feedIo, $feed and $item) to get three different results : two XML-based format and a JSON. This lets you serve all your feeds through three different formats without adding complexity to your code, feed-io handles that for you.

I hope you enjoyed the pieces of code you read and if you want to go further with feed-io, feel free to visit its official website where you will find the whole features list, some code snippets and the API reference.

Licensed under CC BY-NC-SA 4.0
Built with Hugo
Theme Stack designed by Jimmy