Parser is a parser built into PHP to handle XML, and its work consists of three events: start tag, read data, end tag. That is, when the XML is processed, each time the start tag, data and end tag are encountered, the function will do the corresponding action to complete the transformation of the XML data. An introduction to the related functions of XML reading in PHP: Reference: -------------------------------------------------------------------------------- Object XML parsing function description The start and end of the element Xml_set_element_handler () element Start of character data Xml_set_character_data_handler () character data External entity Xml_set_external_entity_ref_handler () external entity appears unresolved external entities xml_set_unparsed_entity_decl_handler () unresolved external entities appear Processing instruction Xml_set_processing_instruction_handler () the appearance of processing instructions Notation Statement Xml_set_notation_decl_handler () The appearance of the notation statement Default Xml_set_default_handler () other events that do not specify a handler function -------------------------------------------------------------------------------- Here is a small example of using the parser function to read XML data:
$parser = Xml_parser_create (); Create a parser editor Xml_set_element_handler ($parser, "startelement", "endElement");//Set the corresponding function when the tag is triggered here are startelement and endelenment respectively Xml_set_character_data_handler ($parser, "characterdata");//Set the corresponding function when reading data $xml _file= "1.xml";//Specifies the XML file to be read, which can be a URL $filehandler = fopen ($xml _file, "R");//Open File while ($data = Fread ($filehandler, 4096)) { Xml_parse ($parser, $data, feof ($filehandler)); }//4,096 bytes per fetch for processing Fclose ($filehandler); Xml_parser_free ($parser);//Close and Release parser parser $name =false; $position =false; function startelement ($parser _instance, $element _name, $attrs)//start tag event functions { Global $name, $position; if ($element _name== "name") { $name =true; $position =false; echo "Name:"; } if ($element _name== "POSITION") {$name =false; $position =true; echo "Position:"; } } function Characterdata ($parser _instance, $xml _data)//functions when reading data { Global $name, $position; if ($position) echo $xml _data. " "; if ($name) echo $xml _data. " "; } function EndElement ($parser _instance, $element _name) function to end tag event { Global $name, $position; $name =false; $position =false; } ?> |
The XML file code is as follows:
Tom Manager John doe Assistant |
The results of this procedure are as follows: Reference: ------------------------------------------------------------------------ Name: Zhang San Position: Manager Name: John Doe Position: Assistant |