PHP SAX Parser Example

please click here for more wordpress cource

Sure, here’s an example of using PHP’s SAX parser to parse an XML file:

class MySAXHandler extends \XMLHandler {
    private $currentElement = null;
    
    public function startElement($parser, $name, $attrs) {
        $this->currentElement = $name;
    }
    
    public function endElement($parser, $name) {
        $this->currentElement = null;
    }
    
    public function characters($parser, $data) {
        if ($this->currentElement == 'title') {
            echo "Title: $data\n";
        } elseif ($this->currentElement == 'author') {
            echo "Author: $data\n";
        }
    }
}

// Create a new parser instance
$parser = xml_parser_create();

// Set the parser options
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);

// Set the handler
$handler = new MySAXHandler();
xml_set_object($parser, $handler);
xml_set_element_handler($parser, 'startElement', 'endElement');
xml_set_character_data_handler($parser, 'characters');

// Parse the XML file
$file = fopen('example.xml', 'r');
while ($data = fread($file, 4096)) {
    xml_parse($parser, $data, feof($file));
}

// Free the parser
xml_parser_free($parser);

This example defines a MySAXHandler class that extends PHP’s built-in XMLHandler class. It overrides the startElement, endElement, and characters methods to handle the XML events that occur during parsing.

In the startElement method, the handler keeps track of the current element being processed.

In the endElement method, the handler resets the current element to null.

In the characters method, the handler checks the current element and prints the data if it’s a title or author element.

The example then creates a new parser instance, sets the options and handlers, and parses an XML file named example.xml.

Finally, the example frees the parser.

You may also like...

Popular Posts

Leave a Reply

Your email address will not be published. Required fields are marked *