theTitle = $rssData;
}
elseif ($curTag == $itemLinkKey) {
$rssArray[$arrayIndex]->theLink = $rssData;
}
elseif ($curTag == $itemDescKey) {
$rssArray[$arrayIndex]->theDescription = $rssData;
// increment item counter
$arrayIndex++;
}
}
//function uses XML parser to parse the document passed as an argument
function parseDocument($link)
{
$parser = xml_parser_create();
xml_set_element_handler($parser, "startElement", "endElement");
//set the character data handler function for the parser, second argument is the
//name of the function that tells the parser about the structure of the document
xml_set_character_data_handler($parser, "rssStructure");
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
//open XML document to extract RSS info
if ( !($fp = fopen($link, "r")) ) {
die ("Could not open RSS document."); }
//string to keep track of current tag
$current_tag = "";
while ($rssData = fread($fp, 4096))
{
//temporarilly replace the & character in link text with the string "ampersand"
//the & character is often handled incorrectly by the XML parser which only
//keeps the token following the last & character
$rssData = str_replace ("&", "ampersand", $rssData);
xml_parse($parser, $rssData, feof($fp));
}
// =========== Close parser and file
xml_parser_free($parser);
fclose($fp);
}
/*** MAIN FUNCTION: This is the function that is called from within the webpage. ***/
//It takes as arguments a string containing the URI of the XML document and an integer
//representing the number of stories the user wants to print out. If you want to print
//all of the stories, pass -1 as the second argument
function printStories($link, $numStories)
{
global $rssArray, $arrayIndex;
parseDocument($link);
//make sure numStories is less than or equal to the size of the array
//so we don't go out of bounds.
if ($numStories > count($rssArray)) {
$numStories = count($rssArray);
}
//if the user enters a negative number, output all the stories
else if ($numStories < 0) {
$numStories = count($rssArray);
}
//print out the stories
for ($i=0 ; $i < $numStories ; $i++)
{
$rssItem = $rssArray[$i];
echo("theLink);
echo("\">");
echo($rssItem->theTitle);
echo("
");
echo(($rssItem->theDescription) . "
");
}
//clear out the array so we can use it again if necessary
$rssArray = array();
//reset the array index
$arrayIndex = 0;
}
?>