#native_company# #native_desc#
#native_cta#

Dynamic XML Conversion Using the SAX Parser Page 4

By PHP Builder Staff
on April 28, 2003

What Is A Stack?

A stack is a simple data structure.
It has two operations: Put data onto stack(“push”) and take data from stack (“pop”).
Imagine a stack of pizza boxes: You can put pizza Nr 1 on the stack, then pizza Nr 2, pizza Nr 3.
When you now take the pizzas from the top of the stack, you get them in reverse order: Pizza 3, Pizza 2, Pizza 1.
Here is the code for the stack:

<?php

$stack
=array();

function push($data) {

    global 
$stack;

    
array_push($stack,$data);

}

function pop() {

    global 
$stack;

    if(
count($stack)==0) {

        die(
"Error: Buffer Underflow!");

    }

    return 
array_pop($stack);

}

?>



In valid XML tags must not overlap, and for every opening tag there is a closing tag. The SAX parser walks through
the script, and for every opening tag it reaches, our script will put its attributes onto the stack. Then, when it
reaches a closing tag, it takes one level from the stack.
So when the parser is converting a document, and it has already processed 13 opening tags and 8 closing tags,
there will be 5 elements on the stack.
As in XML the number of opening tags has to equal the number of closing tags, the stack will be empty when
the parser reaches the end of the document. And as there are no overlapping tags, the data sets are always
fetched in the correct order.
Here is a list of the steps our script will take to walk through a short piece of XML (the XML file contains
no character data, so only the opening and closing functions are called by SAX).
<doc>
	<tag1 parameter="Param 1">
		<tag2 parameter="Param 2">
			<tag3 parameter="Param 3">
			</tag3>
		</tag2>
	</tag1>
</doc>
Parsed element       
<tag1 parameter="Param 1">
<tag2 parameter="Param 2">        
<tag3 parameter="Param 3">        
</tag3>   handle_tag3(pop());
</tag2>   handle_tag2(pop());
</tag1>   handle_tag1(pop());
</doc>    handle_doc(pop());
      
Action
push(array( 'PARAMETER'=>'Param 1'));
push(array('PARAMETER'=>'Param 2'));
push(array('PARAMETER'=>'Param 3'));
//receives array(''PARAMETER'=>'Param 3')
//receives array('PARAMETER'=>'Param 2')
//receives array( 'PARAMETER'=>'Param 1')
//receives array()
      

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