How to Load Images from a RSS Feed using Google Fe

2019-08-12 21:49发布

问题:

I'm not able to load the images using Google Feed API, I'm using the mediaGroup to load images.

This is the javascript code I've written for fetching the feed

<script type="text/javascript">

google.load("feeds", "1");
function initialize() 
   {
    var feed = new google.feeds.Feed("http://techzei.com/feed");
    feed.setNumEntries(14);
    feed.load(function (result) {
        if (!result.error) 
        {
            result.feed.entries.forEach(function(entry)
            {
              $('#feed').append('<div class="card"><a href="' + entry.link + '">' + entry.title + '</a><p>' + entry.contentSnippet + '</p><br><p>'+entry.publishedDate+'"<img src="'+ entry.mediaGroups+'"/></div>');
            });
        }
    });
}
google.setOnLoadCallback(initialize);

The html

<article id="feed"></article>

All the images I get right now are "undefined". Should I be doing something else? The Google Feed API dev didn't throw much light on this

回答1:

That feed doesn't seem to have any mediaGroup entries, that is the reason you get undefined in your result, but you can extract the images from the entry.content using jQuery.

Puts image urls to an array and shows first found image (or none):

var content = document.createElement("content");
content.innerHTML = entry.content;                   
var images = $(content).find('img').map(function(){
    return $(this).attr('src')
}).get();
$('#feed').append('<div class="card"><a href="' + entry.link + '">' +
    entry.title + '</a><p>' + entry.contentSnippet + '</p><br><p>'+ 
    entry.publishedDate +'</p>' + 
    (images.length == 0 ? '' :'<img src="'+ images[0] +'"/>') + '</div>');

Shows all images, by appending the img tags to a variable:

var content = document.createElement("content");
content.innerHTML = entry.content;
var images = "";
$(content).find('img').each(function() {  
    images += this.outerHTML;
}); 
$('#feed').append('<div class="card"><a href="' + entry.link + '">' +
    entry.title + '</a><p>' + entry.contentSnippet + '</p><br><p>' +
    entry.publishedDate + '</p>' + images +'</div>');