This will probably be an easy fix for someone who is familiar with XML. I have gone through the tutorial from this site (XML Parsing using PHP intermediate). Everything is working except for one problem. Every time I refresh my script in my browser, I get a different amount of results. Most times the script only parses 4 results form the xml file but sometimes it parses all 11 results like it should.
Here is what my code looks like:
#################################
?php
$xml_file = “http://api.votesmart.org/Candidates.getByOfficeState?key=72b64124ada95f14e3581b010e133d9b&officeId=5&stateId=UT&electionYear=2008”;
$xml_id_key = “CANDIDATELISTCANDIDATECANDIDATEID";
$xml_ln_key = "CANDIDATELISTCANDIDATELASTNAME”;
$story_array = array();
$counter = 0;
class xml_story{
var $vs_id, $vs_ln;
}
function startTag($parser, $data){
global $current_tag;
$current_tag .= “*$data”;
}
function endTag($parser, $data){
global $current_tag;
$tag_key = strrpos($current_tag, ‘*’);
$current_tag = substr($current_tag, 0, $tag_key);
}
function contents($parser, $data){
global $current_tag, $xml_id_key, $xml_ln_key, $counter, $story_array;
switch($current_tag){
case $xml_id_key:
//$story_array[$counter] = new xml_story();
$story_array[$counter]->vs_id = $data;
break;
case $xml_ln_key:
$story_array[$counter]->vs_ln = $data;
$counter++;
break;
}
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, “startTag”, “endTag”);
xml_set_character_data_handler($xml_parser, “contents”);
$fp = fopen($xml_file, “r”) or die(“Could not open file”);
$size = filesize($xml_file);
$data = fread($fp, 8000) or die(“Could not read file”);
if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
xml_parser_free($xml_parser);
fclose($fp);
?>
<html>
<head>
<title>CNT HEADLINE NEWS</title>
</head>
<body bgcolor="#FFFFFF">
<?php
for($x=0;$x<count($story_array);$x++){
echo " <h2>" . $story_array[$x]->vs_id . "</h2>
";
echo $story_array[$x]->vs_ln . "
";
}
echo “<br><br>”;
print_r($story_array);
echo “<br><br>”;
var_dump($story_array);
?>
</body>
</html>
################################