zeshanshani
8/18/2016 - 5:54 AM

Fetch Google News items of the specified term and display them in an element.

Fetch Google News items of the specified term and display them in an element.

/**
 * Converts XML to JSON
 * Source: https://davidwalsh.name/convert-xml-json
 */
function xmlToJson(xml) {
  
  // Create the return object
  var obj = {};

  if (xml.nodeType == 1) { // element
    // do attributes
    if (xml.attributes.length > 0) {
    obj["@attributes"] = {};
      for (var j = 0; j < xml.attributes.length; j++) {
        var attribute = xml.attributes.item(j);
        obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
      }
    }
  } else if (xml.nodeType == 3) { // text
    obj = xml.nodeValue;
  }

  // do children
  if (xml.hasChildNodes()) {
    for(var i = 0; i < xml.childNodes.length; i++) {
      var item = xml.childNodes.item(i);
      var nodeName = item.nodeName;
      if (typeof(obj[nodeName]) == "undefined") {
        obj[nodeName] = xmlToJson(item);
      } else {
        if (typeof(obj[nodeName].push) == "undefined") {
          var old = obj[nodeName];
          obj[nodeName] = [];
          obj[nodeName].push(old);
        }
        obj[nodeName].push(xmlToJson(item));
      }
    }
  }
  return obj;
};

/**
 * Fetch the Google News
 * 
 * SEARCH_TERM - replace with the search term
 * https://crossorigin.me/ - is used to fix the cross-origin issue.
 */
var FEED_URL = 'https://crossorigin.me/https://news.google.com/news?q=SEARCH_TERM&output=rss';
$.ajax({
  url: FEED_URL,
  // dataType: 'json',
  success: function( data ) {
    var jsonData = xmlToJson(data);
    var items = jsonData.rss.channel.item;
    // Replace the selector you want to append the feed to. 
    // should be <ul> as the output for each item is in <li>
    var newsContainer = $('.news-feed-items');

    $output = '';

    items.forEach( function(item, i) {
      
      var title   = item.title['#text'];
      var desc    = $(item.description['#text']).text();
      var link    = item.link['#text'];
      var pubDate = item.pubDate['#text'];

      $output += '<li>';
      $output +=  '<a href="' + link + '">';
      $output +=  '<h3>' + title + '</h3>';
      $output +=  '<p>' + desc.substr( 0, 133 ) + '...</p>';
      $output +=  '</a>';
      $output += '</li>';

    });

    newsContainer.append( $output ); 

  }
});