|
There are over 10 different XML reports I can download from someone
else's server.
I've made a class to parse the XML into an array. So basically I just
have the start_tag() track what the current tag is, so that my character
handler knows what to do.
Now, say I want to start parsing other XML files, that may have a
different structure, therefore I need to have a separate character
handler (I called it characterDataHandler() below) for each XML report?
What is a good way to extend this class to handle other XML reports?
do a:
class B extends A ?
...then define characterDataHandler() they way I want?
should I think keep going with a:
class C extends A
Surely I don't want to just add a series of characterDataHandler()
functions for each XML report. I think a separate object/class for each
report would make sense, and preserve a one-to-one relationship between
report and class. At least, to me, that would make the most sense?
I consider myself a beginner to these kind of OO design decisions -- I
figure this is a good way to get started.
any suggestions?
################################################## ###########
the code
################################################## ###########
class A {
function A($file)
{
}
function start_tag ($parser, $name, $attrib)
{
//just track what the current tag is
$this->current = $name;
}
function end_tag ($parser, $name)
{
//do nothing, xml_set_element_handler() requires it
}
function characterDataHandler ($parser, $data)
{
//shove the data into an array
}
function parse()
{
$fp=fopen("$this->xml_file", "r")
or die ("Couldn't open XML.");
$this->xml_parser = xml_parser_create()
or die("Couldn't create parser.");
xml_set_object($this->xml_parser, $this);
xml_set_element_handler($this-xml_parser,"start_tag","end_tag");
xml_set_character_data_handler( $this->xml_parser,
"characterDataHandler");
while( $data = fread($fp, 4096))
{
if(!xml_parse($this->xml_parser, $data, feof($fp)))
{
die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code(
$this->xml_parser)),
xml_get_current_line_number($this->xml_parser)));
}
}
xml_parser_free($this->xml_parser);
}
} |