Home > Backend Development > PHP Tutorial > Read xml data with php

Read xml data with php

高洛峰
Release: 2023-03-02 20:28:01
Original
1605 people have browsed it

parser is a parser built into PHP to process XML. Its work consists of three events: start tag, read data, and end tag.
That is to say, when processing xml, whenever the start tag, data and end tag are encountered, the function will take corresponding actions to complete the conversion of xml data.
Introduction to functions related to XML reading in php:
Quote:
Object XML parsing function Description:
Element xml_set_element_handler() The beginning and end of the element
Character data xml_set_character_data_handler() The beginning of character data
External entity xml_set_external_entity_ref_handler() External Entity appears
Unparsed external entity xml_set_unparsed_entity_decl_handler() Unparsed external entity appears
Processing instruction xml_set_processing_instruction_handler() Processing instruction appears
Notation declaration xml_set_notation_decl_handler() Notation declaration appears
Default xml_set_default_handler() Others are not specified event handler function
The following is an example of using the parser function to read xml data:

//Create a parser editor
$parser = xml_parser_create();
//Set up the corresponding function when the tag is triggered Here are: startElement and endElenment
xml_set_element_handler($parser, "startElement", "endElement");
//Set up the corresponding function when reading data
xml_set_character_data_handler($parser, "characterData");
$xml_file="1.xml"; //Specify the xml file to be read, which can be url
$filehandler = fopen($xml_file, "r"); //Open the file
while ($data = fread($filehandler, 4096))
{
xml_parse( $parser, $data, feof($filehandler));
}//Take out 4096 bytes for processing each time
fclose($filehandler);
//Close and release the parser parser
xml_parser_free($parser);
$name=false;
$position=false;
//Function of start tag event
function startElement($parser_instance, $element_name, $attrs)
{
global $name,$position;
if($element_name==
$position=true;
         echo "Website:";                                                                  Echo $xml_data ."
";
if($name)
echo $xml_data."
";
}
//End tag event function
function endElement($parser_instance, $element_name)
{
global $name,$position;
$name=false;
$position=false;
}
?>


The xml file code is as follows:



Website URL
http://www.php.cn




Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template