buildakicker Posted June 7, 2007 Share Posted June 7, 2007 Hello all! I have a parser set up that I cannot grasp my head around why my loop does not work... Here is the code: <?php $insideitem = false; $tag = ""; $title = ""; $description = ""; $link = ""; $counter = 0; 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("<li><a href='%s'>%s</a></li>", trim($link),htmlspecialchars(trim($title))); printf("<dd>%s</dd>",htmlspecialchars(trim($description))); $title = ""; $description = ""; $link = ""; $insideitem = false; } } function characterData($parser, $data) { global $insideitem, $tag, $title, $description, $link; if ($insideitem) { switch ($tag) { case "TITLE": $title .= $data; break; case "LINK": $link .= $data; break; } } } $xml_parser = xml_parser_create(); xml_set_element_handler($xml_parser, "startElement", "endElement"); xml_set_character_data_handler($xml_parser, "characterData"); $fp = fopen("http://www.fs.fed.us/r5/lassen/rss/rss.xml","r") or die("Error reading RSS data."); while($data = fread($fp, 80000) && $counter < 5) { 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))); $counter++; } fclose($fp); xml_parser_free($xml_parser); ?> I am trying to limit the amount of output from the RSS file to just 5 items, or records. I am trying to do this by using a while loop with a count in it when I am showing the feed items. I keep getting an error of: XML error: syntax error at line 1 I don't get it. Any help would be appreciated! Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/54516-php-parser-while-loop-to-limit-amount-of-feeds-read/ Share on other sites More sharing options...
btherl Posted June 7, 2007 Share Posted June 7, 2007 It's saying that you're not giving the parser a valid XML document. Have you checked that $data is really XML? In any case, your loop will limit by number of characters read, not by xml elements. To limit by xml elements you should put the counter inside your tag handlers. You can use static variables or global variables to keep track of the count, same as you are doing with variables like $tag, $description, etc Quote Link to comment https://forums.phpfreaks.com/topic/54516-php-parser-while-loop-to-limit-amount-of-feeds-read/#findComment-269694 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.