I want to parse an XML file (using PHP's built-in XML functions) and store the information in an array. Each XML element has a unique name, but I am having trouble getting the element handler functions to work with global variables, etc.
$file = "connect.xml";
$data_array = array();
function startElement($parser, $name, $attribs) {
global $elename;
$elename = $name;
}
function characterData($parser, $data) {
global $elename;
global $data_array;
echo "$elename - $data<BR>\n";
if (($elename != "") && ($data != "")) {
$data_array[$elename] = $data;
}
}
$xml_parser = xml_parser_create();
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen($file, "r") or die("could not open XML input");
while ($data = fread($fp, 4096)) {
if (!xml_parse($xml_parser, $data, feof($fp))) {
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
}
}
xml_parser_free($xml_parser);
I know it looks messy, but that is the code I have so far. The characterData function is able to see the $elename variable I pulled from the startElement function, but I can't seem to do the command: $data_array[$elename] = $data
an entry in the array is written, but it is only storing "". Any suggestions would be appreciated. Thanks.