PHP: converting RSS to JSON

Converting RSS to JSON requires only a sufficient knowledge of the json_encode() function and one of the XML libraries and extensions that come shipped together with PHP. In this post I'll show you a basic routine to convert an RSS feed to a JSON file using the PHP's DOM extension.

We have only to fetch the feed, parse it and build an associative array to be passed to json_encode():

<?php
header('Content-Type: application/json');
$feed = new DOMDocument();
$feed->load('blog-feed.xml');
$json = array();

$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;

$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');

$json['item'] = array();
$i = 0;


foreach($items as $item) {

   $title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
   $description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
   $pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
   $guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
   
   $json['item'][$i++]['title'] = $title;
   $json['item'][$i++]['description'] = $description;
   $json['item'][$i++]['pubdate'] = $pubDate;
   $json['item'][$i++]['guid'] = $guid;   
     
}


echo json_encode($json);


?>

You can modify the above code as you wish. For example, instead of using the guid element you could use the link element. You can also choose to use another PHP library for this task, such as SimpleXML or XMLReader.

The above code returns the following JSON structure:

{
  "title": "...",
  "description": "...",
  "link": "...",
  "item": [
    {
      "title": "..."
      
    },
    
    {
    
      "description": "..."
      
    },
    
    {
    
      "pubdate" : "..."
      
    },
    
    {
    
      "guid": "..."
      
    }
    
    ... other items
    
  ]

}

Leave a Reply

Note: Only a member of this blog may post a comment.