jQuery: parsing di un feed RSS

jQuery: parsing di un feed RSS

Effettuare il parsing di un feed RSS con jQuery è un'operazione alquanto semplice se si utilizza il metodo $.ajax(). Tutto quello che dobbiamo fare è accedere all'oggetto XMLHttpRequest restituito da questo metodo e selezionare ciascuna voce all'interno del feed (elemento item). Vediamone l'implementazione.

Creiamo un plugin per lo scopo:


(function($) {

  $.fn.RSS = function(options) {
  
    var that = this;
    var settings = {
      url: 'rss.xml'
    };
    
    options = $.extend(settings, options);
    
    return that.each(function() {
    
      $.ajax({
        type: 'GET',
        dataType: 'xml',
        url: options.url,
        success: function(rss) {
        
          var rss = $(rss);
          var html = '';
          var items = rss.find('item');
          var feedTitle = $('channel > title:first-child', rss).text();
          var feedLink = $('channel > title:first-child + link', rss).text();
          var feedDesc = $('channel > title:first-child + link + description', rss).text();
          
          html += '<h1><a href="' + feedLink + '">' + feedTitle + '</a></h1>';
          html += '<div>' + feedDesc + '</div>';
          html += '<ul>';
          
          items.each(function() {
          
            var item = $(this);
            var desc = item.find('description').text();
            var link = item.find('link').text();
            var title = item.find('title').text();
            
            html += '<li><a href="' + link + '">' +
                     title + '</a>' + 
                     '<p>' + desc + '</p></li>';
          
          
          });
          
          html += '</ul>';
          
          that.html(html);
        
        
        }
        
     });
    
    
    });
  
  
  };

})(jQuery);

Impostiamo il tipo di dati (dataType) su xml e accediamo ai vari elementi del feed partendo dall'oggetto XML di tipo DOMDocument restituito dal metodo $.ajax() (qui lo identifichiamo come rss). Usando tale oggetto possiamo selezionare gli elementi item, da cui avremo poi title, link e description operando un ciclo attraverso tutte le voci del feed. Usiamo il metodo text() per accedere al contenuto testuale di ciascun elemento.

Usare il plugin è semplice:


$(function() {

  $('#feed').RSS();  

});

Volendo usare un feed remoto o dinamico, possiamo usare PHP come proxy, per esempio creando il seguente file rss.php:


<?php
header('Content-Type: application/rss+xml');
$feed = file_get_contents('http://feeds.feedburner.com/gabrieleromanato/');
echo $feed;
?>

Quindi è sufficiente usare tale file come URL per il nostro plugin RSS.

Potete visionare l'esempio finale in questa pagina.

Torna su