php parsing rss atom-feed

La mejor forma de analizar feeds RSS/Atom con PHP



parsing atom-feed (10)

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);

Actualmente estoy usando Magpie RSS pero a veces se cae cuando el RSS o el Atom no están bien formados. ¿Hay alguna otra opción para analizar feeds RSS y Atom con PHP?



La biblioteca HTML Tidy puede corregir algunos archivos XML mal formados. Ejecutar sus feeds a través de eso antes de pasarlos al analizador puede ayudar.


Me gustaría introducir un script simple para analizar el 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++; }



Personalmente utilizo BNC Advanced Feed Parser, me gusta el sistema de plantillas que es muy fácil de usar


Si el feed no está bien formado XML, se supone que debes rechazarlo, sin excepciones. Tienes derecho a llamar al creador de fuentes un bozo .

De lo contrario, estás allanando el modo en que se metió el HTML.


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 un feed RSS. Además, detectará advertencias y errores XML, y al encontrar cualquiera, simplemente podría ejecutar la fuente a través de algo como HTML Tidy (como lo mencionó ceejayoz) para limpiarlo e intentarlo de nuevo.

Considere esta clase muy simple y tosca 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; } }



Uso SimplePie para analizar un feed de Google Reader y funciona bastante bien y tiene un conjunto de características decente.

Por supuesto, no lo he probado con feeds RSS / Atom no bien formados, así que no sé cómo lo hace, supongo que los de Google cumplen bastante con los estándares. :)