I have an XML parser script that I wrote based off a tutorial on the web. The tutorial did a decent job of explaining what the pieces do but it did not explain how I could limit my results. This leaves me with the ability to parse the RSS feed and display it on the page but I'm at the mercy of the RSS feed's length as far as showing the headlines on my site though I only want to show 5. You can see what I'm talking about here: XML Parser script.
I was hoping somebody could take a look at the code below and try and point me in the right direction. I tried to incorporate creating a "counter" variable and then throughing a few if statements around different pieces but had no luck.
I have two goals with this script:
Without further ado, here's the script:
<?php
$insideitem = false;
$tag = "";
$title = "";
$description = "";
$link = "";
// FUNCTIONS ###############################################################
function startElement($parser, $name, $attrs)
{
_global $insideitem, $tag, $title, $description, $link;
_if ($insideitem)
_ {
_ _$tag = $name;
_ }
_elseif ($name == "ITEM")
_ {
_ _$insideitem = true;
_ }
}
function endElement($parser, $name)
{
_global $insideitem, $tag, $title, $description, $link;
_if ($name == "ITEM")
_ {
_ _printf("<b><a href='%s' target='_blank'>%s</a></b><br />",
_ _ trim($link),htmlspecialchars(trim($title)));
_ _printf("%s<p class=\"gensmall\" />",htmlspecialchars(trim($description)));
_ _$title = "";
_ _$description = "";
_ _$link = "";
_ _$insideitem = false;
_ _print "$counter";
_ }
}
function characterData($parser, $data)
{
_global $insideitem, $tag, $title, $description, $link;
_if ($insideitem)
_ {
_ _switch ($tag)
_ _ {
_ _ _case "TITLE":
_ _ _$title .= $data;
_ _ _break;
_ _ _case "DESCRIPTION":
_ _ _$description .= $data;
_ _ _break;
_ _ _case "LINK":
_ _ _$link .= $data;
_ _ _break;
_ _ }
_ }
}
// END OF FUNCTIONS #####################################################
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen("http://rss.news.yahoo.com/rss/sports","r")
or die("Error reading RSS data.");
while ( $data = fread($fp, 4096) )
{
_xml_parse($xml_parser, $data, feof($fp))
_ or die(sprintf("XML error: %s at line %d",
_ _xml_error_string(xml_get_error_code($xml_parser)),
_ _xml_get_current_line_number($xml_parser)));
}
fclose($fp);
xml_parser_free($xml_parser);
?>
Update:
Well I was able to limit the RSS feed in 6 story chunks (Why 6, I'm not sure) by using the following with the while statement:
while ( $data = fread($fp, 4096) )
{
if ($counter==1)
{
xml_parse($xml_parser, $data, feof($fp))
or die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
//echo $counter;
$counter++;
}
Still looking to cut the feed down further.[/i]