Initialize the XML parser
We need to initialize the XML parser in PHP, identify different XML processing events, and then parse the XML file.
For example
<? Php
// Initialize the XML parser $ parser = xml_parser_create ();
// Function to use at the start of an elementfunction start ($ parser, $ element_name, $ element_attrs) {switch ($ element_name) {case "NOTE ": echo "Note <br/>"; break; case "TO": echo "To:"; break; case "FROM": echo "From:"; break; case "HEADING": echo "Heading:"; break; case "BODY": echo "Message :";}}
// Function to use at the end of an elementfunction stop ($ parser, $ element_name) {echo "<br/> ";}
// Function to use when finding character datafunction char ($ parser, $ data) {echo $ data ;}
// Specify element handlerxml_set_element_handler ($ parser, "start", "stop ");
// Specify data handlerxml_set_character_data_handler ($ parser, "char ");
// Open XML file $ fp = fopen ("test. xml", "r ");
// Read datawhile ($ data = fread ($ fp, 4096) {xml_parse ($ parser, $ data, feof ($ fp) or die (sprintf ("XML Error: % s at line % d ", xml_error_string (xml_get_error_code ($ parser), xml_get_current_line_number ($ parser )));}
// Free the XML parserxml_parser_free ($ parser );
?>
The output result is as follows.
Note To: ToveFrom: JaniHeading: ReminderMessage: Don't forget me this weekend!
The principle is:
Initialize the XML analyzer and xml_parser_create () functions
Create functions and use different event handlers
Added the xml_set_element_handler () function to specify which functions will be executed, and the parser will encounter opening and closing labels
The xml_set_character_data_handler () function is added to specify which features will be used to analyze character data during execution.
Parse the xml_parse () function of the file "test. xml"
If an error occurs, add the xml_error_string () function to convert the text description of the XML error.
Call the xml_parser_free () function to release the allocated memory and the xml_parser_create () function.
For more information, see www.111cn.net/phper/php.html.