Wednesday, 24 October 2007

Parsing Feed RSS to HTML using MagpieRSS and PHP

This simple tutorial explains how to parse a feed rss to HTML using MagpieRSS and some line of PHP code. MagpieRSS is an XML-based RSS parser in PHP and is included in the download file, into the folder parser.

Download this tutorial


The basic code
Create a new file index.php and copu and paste the following code into the <body> tag. This code parse the feed associated to $url variable in HTML and show in a list (<li> HTML tag) into a PHP page, the links to all items in the feed. In the first line of PHP code, you have to use require_once() to include rss_fetch.inc MagpieRSS file.

<? php
require_once('parser/rss_fetch.inc');
$url = 'http://feeds.feedburner.com/Woork';
$rss = fetch_rss( $url );
echo "Title: " . $rss->channel['title'];
echo "<ul>";
foreach ($rss->items as $item) {
echo "<li>". "<a href=\"". $item['link'] ."\">". $item['title'] ."</a></li>";
}
echo "</ul>";
?>


Limit the number of links to show in HTML
To limit the number of links that you can show in the page you can use a variable $count and a if statement:


<? php
require_once('parser/rss_fetch.inc');
$url = 'http://feeds.feedburner.com/Woork';
$rss = fetch_rss( $url );
echo "Title: " . $rss->channel['title'];
echo "<ul>";
// Limit at only 10 links
$count=1;
foreach ($rss->items as $item) {
echo "<li>". "<a href=\"". $item['link'] ."\">". $item['title'] ."</a></li>";
$count ++;
if($count==10){ break;}
}
echo "</ul>";
?>


Dowload the tutorial and try it!

No comments:

Post a Comment