It's pretty horrific really but as I'm the only one in the office this week who even knows what XML is and the client absolutely NEEDS it this week I had to bash this out. It works but I had one issue when writing it and I wonder if anyone can shed some light on it.
In the character data handler function for some reason I have to use the concatenate operator to get data into the array. When I used the assignment operator it didn't work at all. The array element was there but no data went into it.
What's causing that? Is it something to do with initialising variables?
Code: Select all
$phonesArr = array();
$item = 0;
$element = '';
$features = FALSE;
$featureNum = 0;
// Create an XML parser
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
$fp = fopen("file.xml","r")
or die("Error reading XML 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);
//some whacky XML parsing functions using global vars...
function startElement($parser, $tagName, $attrs){
global $phonesArr, $item, $element, $features, $featureNum;
if($tagName == 'ITEM'){
$item ++;
}
if($tagName =='FEATURES'){
$features = TRUE;
}
if($tagName =='FEATURE'){
$featureNum ++;
}
$element = $tagName;
}
function endElement($parser, $tagName){
global $features, $featureNum;
if($tagName =='FEATURES'){
$features = FALSE;
$featureNum = 0;
}
}
function characterData($parser, $data){
global $phonesArr, $item, $element, $features, $featureNum;
if($features==TRUE){
$phonesArr[$item]['FEATURES'][$featureNum] .= $data;
}else{
$phonesArr[$item][$element] .= $data;
}
}