Actualmente estoy usando Magpie RSS, pero a veces se cae cuando el feed RSS o Atom no está bien formado. ¿Hay alguna otra opción para analizar fuentes RSS y Atom con PHP?
Actualmente estoy usando Magpie RSS, pero a veces se cae cuando el feed RSS o Atom no está bien formado. ¿Hay alguna otra opción para analizar fuentes RSS y Atom con PHP?
Sus otras opciones incluyen:
Siempre he usado las funciones SimpleXML integradas en PHP para analizar documentos XML. Es uno de los pocos analizadores genéricos que tiene una estructura intuitiva, lo que hace que sea extremadamente fácil crear una clase significativa para algo específico como una fuente RSS. Además, detectará advertencias y errores XML, y al encontrarlos, simplemente puede ejecutar la fuente a través de algo como HTML Tidy (como mencionó ceejayoz) para limpiarlo e intentarlo nuevamente.
Considere esta clase simple y muy aproximada usando SimpleXML:
class BlogPost
{
var $date;
var $ts;
var $link;
var $title;
var $text;
}
class BlogFeed
{
var $posts = array();
function __construct($file_or_url)
{
$file_or_url = $this->resolveFile($file_or_url);
if (!($x = simplexml_load_file($file_or_url)))
return;
foreach ($x->channel->item as $item)
{
$post = new BlogPost();
$post->date = (string) $item->pubDate;
$post->ts = strtotime($item->pubDate);
$post->link = (string) $item->link;
$post->title = (string) $item->title;
$post->text = (string) $item->description;
// Create summary as a shortened body and remove images,
// extraneous line breaks, etc.
$post->summary = $this->summarizeText($post->text);
$this->posts[] = $post;
}
}
private function resolveFile($file_or_url) {
if (!preg_match('|^https?:|', $file_or_url))
$feed_uri = $_SERVER['DOCUMENT_ROOT'] .'/shared/xml/'. $file_or_url;
else
$feed_uri = $file_or_url;
return $feed_uri;
}
private function summarizeText($summary) {
$summary = strip_tags($summary);
// Truncate summary line to 100 characters
$max_len = 100;
if (strlen($summary) > $max_len)
$summary = substr($summary, 0, $max_len) . '...';
return $summary;
}
}
$feed_uri = $feed_or_url;
a $feed_uri = $file_or_url;
... aparte de eso, ¡gracias por este código! ¡Funciona muy bien!
Con 4 líneas, importo un rss a una matriz.
$feed = implode(file('http://yourdomains.com/feed.rss'));
$xml = simplexml_load_string($feed);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
Para una solución más compleja
$feed = new DOMDocument();
$feed->load('file.rss');
$json = array();
$json['title'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$json['description'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$json['link'] = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $key => $item) {
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$description = $item->getElementsByTagName('description')->item(0)->firstChild->nodeValue;
$pubDate = $item->getElementsByTagName('pubDate')->item(0)->firstChild->nodeValue;
$guid = $item->getElementsByTagName('guid')->item(0)->firstChild->nodeValue;
$json['item'][$key]['title'] = $title;
$json['item'][$key]['description'] = $description;
$json['item'][$key]['pubdate'] = $pubDate;
$json['item'][$key]['guid'] = $guid;
}
echo json_encode($json);
$feed = file_get_contents('http://yourdomains.com/feed.rss');
podría ser menos intenso que file +
Me gustaría presentar un script simple para analizar RSS:
$i = 0; // counter
$url = "http://www.banki.ru/xml/news.rss"; // url to parse
$rss = simplexml_load_file($url); // XML parser
// RSS items loop
print '<h2><img style="vertical-align: middle;" src="'.$rss->channel->image->url.'" /> '.$rss->channel->title.'</h2>'; // channel title + img with src
foreach($rss->channel->item as $item) {
if ($i < 10) { // parse only 10 items
print '<a href="'.$item->link.'">'.$item->title.'</a><br />';
}
$i++;
}
Si el feed no está bien formado XML, se supone que debe rechazarlo, sin excepciones. Tienes derecho a llamar al creador de feeds un bozo .
De lo contrario, está allanando el camino para desordenar en el que terminó HTML.
La biblioteca HTML Tidy puede reparar algunos archivos XML con formato incorrecto. Ejecutar sus feeds antes de pasarlos al analizador puede ayudar.
Personalmente uso BNC Advanced Feed Parser, me gusta el sistema de plantillas que es muy fácil de usar.
El lector RSS de PHP - http://www.scriptol.com/rss/rss-reader.php - es un analizador completo pero simple utilizado por miles de usuarios ...
Otro gran analizador gratuito: http://bncscripts.com/free-php-rss-parser/ ¡ Es muy ligero (solo 3kb) y fácil de usar!