I'm parsing an XML file using the expat functions, and trying to dynamically build a complex array to represent the document's structure, such that
<EMPLOYEE>
<CONTACT_INFO>
<WORK>555-3434</WORK>
<CELL>555-1212</CELL>
</CONTACT_INFO>
</EMPLOYEE>
<EMPLOYEE>
...
<EMPLOYEE>
is represented as follows:
$tree['EMPLOYEE'][0]['CONTACT_INFO'][0]['WORK'][0] = '555-3434'. Each has a numeric subscript because any element may repeat in the XML doc.
The code that adds elements to the array is in the startElement handler, and is similar to the following:
<?
$tree = array();
$ptr =& $tree; // initialize tree pointer
function addElement($string) {
global $ptr;
$name = trim($string); //$name contains the XML element name
$ptr[$name][] = array(); //if $tree['EMPLOYEE'][0] already exists, this should create a new array at $tree['EMPLOYEE'][1];
$lastIndex = count($ptr[$name])-1;
$ptr =& $ptr[$name][$lastIndex]; //point to array element just added
return;
}
This does not work as expected. It seems to create an array with all elements directly attached to $tree ($tree['WORK'][0] rather than $tree['EMPLOYEE'][0]['CONTACT_INFO'][0]['WORK'][0], etc.).
The confusing thing is that this code algorigm works in simple iteration, without the function call. The following produces the desired results:
$tree = array();
$ptr =& $tree;
$name = 'EMPLOYEE';
$ptr[$name][] = array();
$lastIndex = count($ptr[$name])-1;
$ptr =& $ptr[$name][$lastIndex];
$name = 'CONTACT_INFO';
$ptr[$name][] = array();
$lastIndex = count($ptr[$name])-1;
$ptr =& $ptr[$name][$lastIndex];
$name = 'WORK';
$ptr[$name][] = array();
$lastIndex = count($ptr[$name])-1;
$ptr =& $ptr[$name][$lastIndex];
$ptr = "555-3434";
print($tree['EMPLOYEE'][0]['CONTACT_INFO'][0]['WORK'][0]);
?>
the above produces: 555-3434
So I suspect that the problem has to do with the way global variables are handled in function calls, but I can't put my finger on it. Any help would be greatly appreciated.