/*
A PHP block with code that accesses the Dilbert RSS feed and returns
a set number of cartoons.
Original RSS feed code author unknown.
Adapted by freddy888 March 2010
@ Tiny Portal - http://www.tinyportal.net/index.php?topic=32155
Version 1.2
*/
global $cartoonCount, $cartoonLimit;
// Set this to how many cartoons you want to display.
$cartoonLimit = 1;
// Set the feed where Dilbert is located.
$rssFeed = "http://feeds.dilbert.com/DilbertDailyStrip?format=xml";
// Will count the number of cartoons found.
$cartoonCount = 0;
DIL_readFeeds($rssFeed);
function DIL_start_Element($xp, $name, $attributes)
{
global $item,$currentElement; $currentElement = $name;
//the other functions will always know which element we're parsing
if ($currentElement == 'ITEM')
{
//by default PHP converts everything to uppercase
$item = true;
// We're only interested in the contents of the item element.
// This flag keeps track of where we are
}
}
function DIL_end_Element($xp,$name)
{
global $item, $currentElement, $title, $description, $link, $pubdate, $cartoonCount, $cartoonLimit;
// Are we at the end of the item element ?
if ($name == 'ITEM')
{
// Are we below the cartoon limit, if we are display the cartoon.
if ($cartoonCount < $cartoonLimit)
{
// Remove and tags in the title.
$title = strip_tags($title);
// Remove everything apart from images.
$description = strip_tags($description, '<img>');
// Find the end of the first image which is the cartoon.
$firstImageEnd = stripos($description, '>');
// Extract the cartoon image only, which happens to be first.
$cartoon = substr($description, 0, $firstImageEnd + 1);
// Insert alt and title attributes
$cartoon = str_replace('/>', 'alt="Dilbert ' . $title . '" title="Dilbert ' . $title . '" />', $cartoon);
// Display the cartoon/
echo '
<div style="margin: 15px; text-align: center">
<a href="' , $link , '" target="_blank">' , $cartoon , '</a>
</div>';
}
// Reset globals
$title = '';
$description = '';
$link = '';
$pubdate = '';
$item = false;
$cartoonCount += 1;
}
}
function DIL_characterDataHandler($xp,$data)
{
global $item, $currentElement, $title, $description, $link, $pubdate;
if ($item)
{
//Only add to the globals if we're inside an item element.
switch($currentElement)
{
case "TITLE":
$title .= $data;
// We use .= because this function may be called multiple
// times for one element.
break;
case "DESCRIPTION":
$description.=$data;
break;
case "LINK":
$link.=$data;
break;
case "PUBDATE":
$pubdate.=$data;
break;
}
}
}
function DIL_readFeeds($feed)
{
$fh = fopen($feed,'r');
// open file for reading
$xp = xml_parser_create();
// Create an XML parser resource
xml_set_element_handler($xp, "DIL_start_Element", "DIL_end_Element");
// defines which functions to call when element started/ended
xml_set_character_data_handler($xp, "DIL_characterDataHandler");
while ($data = fread($fh, 4096))
{
if (!xml_parse($xp,$data))
{
return 'Error in the feed';
}
}
xml_parser_free($xp);
}