Im trying to parse through an XML doc and am having an issue with empty element tags.
My XML:
<?xml version="1.0" encoding="ISO-8859-1"?>
<getReviews>
<review>
<image>Image Name 1</image>
<title>Title 1</title>
<url>URL 1</url>
<award>Award 1</award>
<description></description>
</review>
<review>
<image>Image Name 2</image>
<title>Title 2</title>
<url>URL 2</url>
<award>Award 2</award>
<description></description>
</review>
</getReviews>
The PHP im using is only returning one result when I output the results. This is because of . Since there is nothing in , it isn’t closing out the result. How can I get it to do this?
Here is my PHP:
$xml_file = "xml/getReviews.xml";
$xml_image_key = "*GETREVIEWS*REVIEW*IMAGE";
$xml_title_key = "*GETREVIEWS*REVIEW*TITLE";
$xml_url_key = "*GETREVIEWS*REVIEW*URL";
$xml_award_key = "*GETREVIEWS*REVIEW*AWARD";
$xml_description_key = "*GETREVIEWS*REVIEW*DESCRIPTION";
$review_array = array();
$counter = 0;
class xml_getReviews{
var
$image,
$title,
$url,
$award,
$description;
}
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_image_key,
$xml_title_key,
$xml_url_key,
$xml_award_key,
$xml_description_key,
$counter,
$review_array;
switch($current_tag){
case $xml_image_key:
$review_array[$counter] = new xml_getReviews();
$review_array[$counter]->image = $data;
break;
case $xml_title_key:
$review_array[$counter]->title = $data;
break;
case $xml_url_key:
$review_array[$counter]->url = $data;
break;
case $xml_award_key:
$review_array[$counter]->award = $data;
break;
case $xml_description_key:
$review_array[$counter]->description = $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");
$data = fread($fp, filesize($xml_file)) 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);
for($x=0;$x<count($review_array);$x++){
//
echo $review_array[$x]->image."<BR>";
echo $review_array[$x]->title."<BR>";
echo $review_array[$x]->url."<BR>";
echo $review_array[$x]->award."<BR>";
echo $review_array[$x]->description."<BR>";
//
}
My output is:
Image Name 2
Title 2
URL 2
Award 2