Possiamo creare un lettore di feed RSS dinamico con PHP usando come parametri dell'URL passato al nostro script l'indirizzo del feed RSS e il numero massimo di elementi da restituire. Il nostro script genererà una semplice struttura HTML che potrà essere usata come meglio crediamo. Vediamo insieme i dettagli dell'implementazione.
L'URL passato allo script e il numero di elementi richiesto devono essere validati prima di poter essere usati. Di seguito mostro alcune routine di validazione, che ovviamente potete estendere e migliorare:
$feedURL = $_GET['u'];
$limit = $_GET['items'];
$html = '';
$cnt = '';
if(filter_var($feedURL, FILTER_VALIDATE_URL)) {
if(file_get_contents($feedURL)) {
$ch = curl_init($feedURL);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
try {
$doc = new SimpleXmlElement($data, LIBXML_NOCDATA);
} catch(Exception $e) {
$html = '<p>Error: Invalid XML.</p>' . "\n";
echo $html;
exit();
}
if(isset($doc->channel)) {
$html = '<div class="feed">' . "\n";
$html .= '<h2>' . $doc->channel->title . '</h2>' . "\n";
$items = count($doc->channel->item);
if(isset($limit)) {
if(is_numeric($limit)) {
if($limit < $items) {
$cnt = $limit;
} else {
$html = '<p>Error: too many items requested.</p>' . "\n";
echo $html;
exit();
}
} else {
$html = '<p>Error: items must be a number.</p>' . "\n";
echo $html;
exit();
}
} else {
$cnt = $items;
}
for($i=0; $i<$cnt; $i++) {
$url= $doc->channel->item[$i]->link;
$title= $doc->channel->item[$i]->title;
$desc = $doc->channel->item[$i]->description;
$date = $doc->channel->item[$i]->pubDate;
$html .= '<div class="entry">' . "\n";
$html .= '<h3><a href="' . $url . '">' . $title . '</a></h3>' . "\n";
$html .= '<div class="date">' . $date . '</div>' . "\n";
$html .= '<p>' . $desc . '</p>' . "\n";
$html .= '</div>' . "\n";
}
$html .= '</div>' . "\n";
} else {
$html = '<p>Error: This is not an RSS feed.</p>' . "\n";
}
} else {
$html = '<p>Error: File Not Found.</p>' . "\n";
}
} else {
$html = '<p>Error: Invalid URL.</p>' . "\n";
}
echo $html;
Abbiamo usato un approccio molto semplice (se vogliamo anche semplicistico) per la gestione degli errori: abbiamo infatti verificato che l'URL passato sia attivo, che la risorsa esista e che l'XML del documento sia valido.
Una migliore implementazione potrebbe ad esempio ottenere il numero di elementi item
presenti nel feed e compararlo con il numero specificato nel parametro items
. Quindi se il feed ha solo 10 voci, un URL del genere:
http://sito.it/script.php?u=http://sito2.it/feed/rss&items=20
restituirebbe un errore, perchè le voci specificate sono 20.