#native_company# #native_desc#
#native_cta#

Dynamic XML Conversion Using the SAX Parser Page 5

By PHP Builder Staff
on April 28, 2003

The element handling functions
These functions are called by the SAX parser.
These are the handling functions for opening tags and character data:

<?php

function tag_open($parser$name$attrs)

{

    
push(array("attrs"=>$attrs"contents"=>""));

}

function cdata($parser,$string) {

    
// Fetch from Stack, insert the character data, and put it back

    
$data=pop();

    
$data["contents"].=$string;

    
push($data);

}

?>



In addition to the attribute list we also store the character data inside the tag into the stack.
The tag closing function is the most complicated part of the script. It works like this:
  1. Pop the parameters and content from the stack
  2. If a conversion function exists for this tag, call it and pass it the attributes and contents.Save its return value. If no conversion function is assigned to the current tag, rebuild the original tag
  3. Pop the next set of data from the stack (the data of the tag surrounding the current one)
  4. Add the saved return value to its contents data
  5. Put it back onto the stack

<?php

function tag_close($parser,$name) {

    
$function="handle_".strtolower($name);

    
$data=pop();

    

    if(
function_exists($function)) {

        
$buffer=call_user_func($function,$data["contents"],$data["attrs"]);

    }

    else {

        
$buffer=create_xml_tag($name$data["attrs"], $data["contents"]);

    }

    
$sublevel=pop();

    
$sublevel["contents"].=$buffer;

    
push($sublevel);



?>



Character data is passed through, as are tags that are not handled by a conversion function.
So you don’t have to write a handling function for every tag in your document, because they
stay unchanged. You can take a valid XHTML document as input for the converter, and the output
will be the same document except for the tags replaced by your conversion functions.

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