immagine decorativa

Semplice parser RSS in AJAX

Questo codice, fornito così com'è e senza nessuna garanzia è un semplicissimo parser RSS che mostra la notizia più recente inserita in un determinato feed. L'ho pensato come display per integrare Twitter in un sito o in un blog.

È realizzato in JavaScript, ed utilizza uno script php server-side per il caching dell'RSS (funzionalità molto utile per Twitter, visto che è particolarmente lento, di tanto in tanto).

Per esigenze di impaginazione il codice è stato mandato «a capo» un po' di volte (anche dove non avrebbe dovuto). Ripristinate gli «a capo» se avete intenzione di utilizzare il codice.

Pagina HTML che ospita il feed

È necessario far caricare lo script all'apertura della pagina (attributo onload del tag body), chiamando la funzione getRSS(). Si deve quindi inserire, dove si vuol far apparire il feed, il seguente div:

<div id="rssdisplay">
  <script language="javascript" src="rssajax/poluzrss.js"></script>
  <noscript>È necessario avere JavaScript attivato per usufruire di questo servizio.</noscript>
</div>

poluzrss.js

Si cura del parsing e della visualizzazione dell'rss inviato dallo script getCachedRss.php. throbber.gif è un'immagine che viene mostrata nell'attesa dell'rss e del suo parsing, potete trovare alcuni spunti qui: http://swik.net/Ajax/Ajax+Images

/*
    @author: Nicola Poluzzi
    @website: http://www.poluz.net/materiale:rss-ajax-parser
 
    Copyright (C) 2007  Nicola Poluzzi
 
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.
 
    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.
 
    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
 
 
function getRSS () {
    // al caricamento, mostra il throbber per alleggerire l'attesa
    document.getElementById("rssdisplay").innerHTML +=
        "<img src='rssajax/throbber.gif' alt='(t)' /> Caricamento...";
 
    // carico l'xml chiamando lo script php
    if (window.ActiveXObject) {
        //IE
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        //altri
        xhr = new XMLHttpRequest();
    } else {
        document.getElementById("rssdisplay").innerHTML =
        "Si è verificato un errore nella ricezione delle informazioni";
    }
 
    xhr.open("GET", "rssajax/getCachedRss.php", true);
 
    xhr.setRequestHeader("Cache-Control", "no-cache");
    xhr.setRequestHeader("Pragma", "no-cache");
 
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            if (xhr.status == 200) {
                if (xhr.responseText != null) {
                    processRSS(xhr);
                } else {
                    document.getElementById("rssdisplay").innerHTML
                    += "Impossibile ricevere le informazioni. Il server ha
                    restituito una risposta vuota.";
                    return false;
                }
            } else {
                document.getElementById("rssdisplay").innerHTML +=
                "Ricevuto un errore " + xhr.status + ": " + xhr.statusText;
            }
        }
    }
 
    xhr.send(null);
}
 
/////////////////////////////
 
// legge e stampa la prima notizia del feed rss
function processRSS (xmlhttp) {
	var rssxml = xmlhttp.responseXML;
 
    var elemento = rssxml.getElementsByTagName("item")[0];
 
    var descrizione =
        elemento.getElementsByTagName("description")[0].firstChild.nodeValue;
    var data = elemento.getElementsByTagName("pubDate")[0].firstChild.nodeValue;
    var link = elemento.getElementsByTagName("link")[0].firstChild.nodeValue;
 
    descrizione = descrizione.substring(7) + "<br /<br />";
    var datalink = "<a href='" + link + "'>" + data + "</a>";
 
    var rsshtml = descrizione + datalink;
 
    document.getElementById("rssdisplay").innerHTML = rsshtml;
 
    return true;
 
}

getCachedRss.php

<?php
 
	/*
	    Questo script carica il file RSS (XML) desiderato e, tramite il
	    caching su file di quest'ultimo, evita di effettuare troppe
	    richieste al webserver.
 
	    @author: Nicola Poluzzi
	    @website: http://www.poluz.net
	    @date: 2007-02-13
 
	    Copyright (C) 2007  Nicola Poluzzi
 
	    This program is free software; you can redistribute it and/or modify
	    it under the terms of the GNU General Public License as published by
	    the Free Software Foundation; either version 2 of the License, or
	    (at your option) any later version.
 
	    This program is distributed in the hope that it will be useful,
	    but WITHOUT ANY WARRANTY; without even the implied warranty of
	    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	    GNU General Public License for more details.
 
	    You should have received a copy of the GNU General Public License along
	    with this program; if not, write to the Free Software Foundation, Inc.,
	    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
	*/
 
	// ###### PARAMETRI  DI  CONFIGURAZIONE ######
 
	// URI del file RSS (XML)
	$rssUri = "http://twitter.com/statuses/user_timeline/634773.rss";
	// Timeout della cache in secondi
	$cacheLife = 1200;
	// Path del file di cache
	$cachePath = "";
 
	// ###### FINE  PARAMETRI  DI  CONFIGURAZIONE ######
 
 
	// ###############################################
	// ######   NON  MODIFICARE  QUI  SOTTO  !! ######
	// ###############################################
 
	$cacheFileName = "cache.txt";
	$cacheFile = $cachePath . $cacheFileName;
 
 
	/* 	Effettua la richiesta del documento
		$rssUri: l'URI del file XML da caricare
		ritorna: il DOMDocument con il file XML caricato
	*/
	function loadFile($rssUri) {
		$documento = new DOMDocument();
		$documento->load($rssUri);
		return $documento->saveXML();
	}
 
	/*
	    Gestisce il caching dell'rss e la sua ricezione da remoto
	    in caso di cache assente o vecchia
	    $rssUri: l'URI del file XML da caricare
	    $cacheFile: il file, completo di percorso di directory, 
	    un cui salvare la cache
	    $cacheLife: la vita in secondi della cache
	    ritorna: la stringa con l'XML dell'rss
	*/
	function requestCache($rssUri, $cacheFile, $cacheLife) {
		if (!file_exists($cacheFile) || filemtime($cacheFile)
		< (time() - $cacheLife)) {
			// la cache non esiste oppure è scaduta
			$data = loadFile($rssUri);
			$fp = fopen($cacheFile, "w");
			fwrite($fp, $data);
			fclose($fp);
			return $data;
		} else {
			// la cache è presente e «attuale»
			$data = file_get_contents($cacheFile);
			return $data;
		}
	}
 
	header("Content-Type: text/xml");
	echo requestCache($rssUri, $cacheFile, $cacheLife);
 
?>

Soluzione alternativa (in assenza di DOM o con php 4)

In caso di problemi con le funzioni DOM di php (soprattutto nel caso di servizi di hosting che non le forniscano), e per il funzionamento dello script con php4, è sufficiente modificare la funzione loadFile() del file getCachedRss.php nel seguente modo, sicuramente meno elegante, ma comunque funzionale:

function loadFile($rssUri) {
    return file_get_contents($rssUri);
}

Annotazioni varie

  • La gestione della concorrenza degli accessi su cache.txt dovrebbe, in teoria, essere fatta dal sistema operativo stesso. Sarà vero?
  • Il sistema di caching può essere applicato a qualsiasi file XML, non solo agli RSS. Con poche modifiche, si può applicare un po' a tutto.
Non mi assumo nessuna responsabilità per qualsiasi tipo di danno derivante dall'uso di questo codice. Prima di usarlo, è vostra responsabilità verificare che sia veramente corretto e sicuro.
Se hai voglia di scrivermi… fai!
Entra