Parser is a php built-in parser used to process xml. its work consists of three events: start tag, read data, and end tag. Parser is a php built-in parser used to process xml. its work consists of three events: start tag, read data, and end tag.
That is to say, when processing xml, the function performs the corresponding action to complete the conversion of xml data whenever the start tag, data, and end tag are encountered.
Introduction to functions related to xml reading in php:
Reference:
Object XML parsing function description:
Start and end of element xml_set_element_handler ()
Character data xml_set_character_data_handler () start of character data
External entity xml_set_external_entity_ref_handler () external entity appears
External entity xml_set_unparsed_entity_decl_handler () not resolved external entity appears
Processing Command xml_set_processing_instruction_handler () processing command appears
The emergence of the xml_set_notation_decl_handler () method declaration
By default, xml_set_default_handler () is used for events that do not specify a processing function.
The following is an example of using the parser function to read xml data:
// Create a parser editor $ Parser = xml_parser_create (); // The corresponding functions for tag setting triggering are startElement and endElenment respectively. Xml_set_element_handler ($ parser, "startElement", "endElement "); // Set up the corresponding function for data reading Xml_set_character_data_handler ($ parser, "characterData "); $ Xml_file = "1.xml"; // specify the xml file to be read, which can be a url $ Filehandler = fopen ($ xml_file, "r"); // open the file While ($ data = fread ($ filehandler, 4096 )) { Xml_parse ($ parser, $ data, feof ($ filehandler )); } // Extract 4096 bytes each time for processing Fclose ($ filehandler ); // Close and release the parser Xml_parser_free ($ parser ); $ Name = false; $ Position = false; // Function of the start tag event Function startElement ($ parser_instance, $ element_name, $ attrs) { Global $ name, $ position; If ($ element_name = "NAME "){ $ Name = true; $ Position = false; Echo "name :"; } If ($ element_name = "POSITION "){ $ Name = false; $ Position = true; Echo "URL :"; } } // Function used to read data Function characterData ($ parser_instance, $ xml_data) { Global $ name, $ position; If ($ position) Echo $ xml_data ." "; If ($ name) Echo $ xml_data ." "; } // End the tag event function Function endElement ($ parser_instance, $ element_name) { Global $ name, $ position; $ Name = false; $ Position = false; } ?> |
The xml file code is as follows:
Website Name Php self-learning network Website URL Http://www.phpzixue.cn |