This snippet explains how you can read and parse RSS feeds with Google Apps Script. The script reads the feed using URLFetchApp, translates the RSS Feed and then serves it as an RSS feed using the ContentService (the mime type is set to RSS).
Also, the feed content is cached for an hour to reduce the number of URL fetch requests.
function doGet() {
var fromLang = 'en';
var toLang = 'fr';
var rssFeed = 'http://feeds.labnol.org/';
var feed = parseRSS(rssFeed, fromLang, toLang);
return ContentService.createTextOutput(feed).setMimeType(ContentService.MimeType.RSS);
}
function parseRSS(feed, fromLang, toLang) {
var id = Utilities.base64Encode(feed + fromLang + toLang);
// Cache the RSS feeds for an hour
var cache = CacheService.getPublicCache();
var rss = cache.get(id);
if (rss != null) {
return rss;
}
var item, date, title, link, desc, guid;
var txt = UrlFetchApp.fetch(feed).getContentText();
var doc = Xml.parse(txt, false);
title = doc.getElement().getElement('channel').getElement('title').getText();
// The RSS Feed is translated using Google Translate
rss = '';
rss += '';
rss += LanguageApp.translate(title, fromLang, toLang);
rss += ' (' + title + ')';
var items = doc.getElement().getElement('channel').getElements('item');
// Parsing single items in the RSS Feed
for (var i in items) {
try {
item = items[i];
title = item.getElement('title').getText();
link = item.getElement('link').getText();
date = item.getElement('pubDate').getText();
desc = item.getElement('description').getText();
guid = Utilities.base64Encode(link + fromLang + toLang);
title = LanguageApp.translate(title, fromLang, toLang);
desc = LanguageApp.translate(desc, fromLang, toLang, { contentType: 'html' });
rss += '';
rss += ' ' + title + '';
rss += ' ' + link + '';
rss += ' ' + date + '';
rss += ' ' + guid + '';
rss += ' ';
rss += '';
} catch (e) {
Logger.log(e);
}
}
rss += '';
cache.put(id, rss, 3600);
return rss;
}