Converting XML Into a PHP Data Structure - Building the Array Tree (Page 6 of 9 )
At this point, we have a functioning class that will parse an XML document and fire events.
What we'll need to do now is modify the event handlers to build our array tree using the array structure we defined above.
A simple algorithm for developing this code goes as follows:
Each time a 'START' event is called, build a new node. The node we are building is our array structure, but you might decide to build a Node object using your own custom objects. The START event contains the name and attributes of the tag. After building the node, push the new node onto a class-level stack so that we can add data and sub-nodes from the 'DATA' or 'END' elements later.
Each time a 'DATA' event is called, append the text to the end of the text inside the node which is currently on top of our stack.
Each time an 'END' event is called, we need to pop a node off the stack, finalize the node, and add it as a subnode to the node which is now on the top of the stack. This completes the depth-first build of our tree structure.
Before we start parsing the XML, it might help to push a 'root' node onto an empty stack. This way, when the parsing is completed, we expect to find only the root node remaining on the stack with all the subnodes built beneath it.