XML parsing class, variable losing it's value
Posted: Mon May 21, 2007 2:17 pm
I've spent hours trying to figure out why a member variable of this parsing class I'm working on is losing it's value. I've showed it to a few people and nobody has been able to figure it out yet. I would greatly appreciate if someone could shed some light on what is going on here....
So, I'm creating a parsing class to read in an XML file for a web surveying script I'm working on. Part of what I need the class to do is assign the question's text to a variable called $qtext which is done by reading in the value between the TEXT tags.
Here is the Parser class I'm using to determine the cause of this problem. The area to focus on is the characterdata function, where I assign the value of $data to member variable $qtext if the tag is TEXT.
Here is the XML code that is being used:
And here is the output I get. Notice the value of $qtext does not get printed after the Text tag closes, even though it should. The value of $qtext seems to disappear after that tag is closed, but I have no idea why. The $num variable retains its value. Help!! 
So, I'm creating a parsing class to read in an XML file for a web surveying script I'm working on. Part of what I need the class to do is assign the question's text to a variable called $qtext which is done by reading in the value between the TEXT tags.
Here is the Parser class I'm using to determine the cause of this problem. The area to focus on is the characterdata function, where I assign the value of $data to member variable $qtext if the tag is TEXT.
Code: Select all
<?php
class Parser {
var $insideq;
var $tag="";
var $qtext="";
var $num=0;
function startElement($parser,$tagname,$attr) {
$this->tag=$tagname;
echo $tagname . "<br>";
echo $this->qtext;
}
function characterData($parser, $data) {
if ($this->tag=="TEXT") {
$this->qtext=$data;
$this->num=1;
}
echo $this->qtext;
echo $this->num;
}
function endElement($parser,$tagname) {
if ($tagname=="SELECTONE") {
echo $this->qtext;
}
echo $this->qtext;
echo "\\" . $tagname . "<br>";
}
}
$xml_parser = xml_parser_create();
$parser = new Parser();
xml_set_object($xml_parser,&$parser);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen("mytestxml.php","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);
?>Code: Select all
<SELECTONE>
<TEXT>Testing text</TEXT>
<punch>This is not the text tag</punch>
<PUNCH></PUNCH>
<PUNCH></PUNCH>
</SELECTONE>SELECTONE
0TEXT
Testing text1Testing text\TEXT
1PUNCH
1 \PUNCH
1PUNCH
\PUNCH
1PUNCH
\PUNCH
1 \SELECTONE