#native_company# #native_desc#
#native_cta#

Converting XML into a PHP data structure Page 4

By PHP Builder Staff
on December 25, 2002

Make PHP Do The Hard Work

PHP has a built-in process for parsing your XML document. You pass a string
to the xml_parse function with XML text in it and when the
XML document is parsed, handlers for the configured events are called
as many times as necessary. Some events for which you can write handlers
are ‘StartElement’, ‘EndElement’, and ‘CharacterData’. Here is some sample
code for definine a class and the three event handlers to parse XML:

<?php

//######################################################################

class XMLToArray {

    var $parser;

    //----------------------------------------------------------------------

    /* Parse a text string containing valid XML into a multidim array. */

    
function parse($xmlstring="") {

        
// set up a new XML parser to do all the work for us

        
$this->parser xml_parser_create();

        
xml_set_object($this->parser$this);

        
xml_parser_set_option($this->parserXML_OPTION_CASE_FOLDINGfalse);

        
xml_set_element_handler($this->parser"startElement""endElement");

        
xml_set_character_data_handler($this->parser"characterData");

        // parse the data and free the parser...

        
xml_parse($this->parser$xmlstring);

        
xml_parser_free($this->parser);

        // ...

    
}

    //----------------------------------------------------------------------

    
function startElement($parser$name$attrs) {

        
// Start a new Element.  This means we push the new element onto

        // the stackand reset it's properties.

        
printf("START: [%s]n"$name);

        // ...

    
}

    //----------------------------------------------------------------------

    
function endElement($parser$name) {

        
// End an element.  This is done by popping the last element from

        // the stack and adding it to the previous element on the stack.

        
printf("END: [%s]n"$name);

        // ...

    
}

    //----------------------------------------------------------------------

    
function characterData($parser$data) {

        
// Collect the data onto the end of the current chars.

        
printf("DATA: [%s]n"str_replace("n"""$data));

        // ...

    
}

    //----------------------------------------------------------------------

}

//######################################################################

?>



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