#native_company# #native_desc#
#native_cta#

Converting XML into a PHP data structure Page 7

By PHP Builder Staff
on December 25, 2002

Building The Array Tree

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.

1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|