xml_parse
Start parsing XML documents
xml_parse() function is used to parse XML documents.
Tip: To create an XML parser, use xml_parser_create() function.
Create an XML parser and parse the XML document ( note.xml ):
<?php
// Create XML parser
$parser = xml_parser_create ( ) ;
function char ( $parser , $data ) {
echo $data ;
}
xml_set_character_data_handler ( $parser , "char" ) ;
$fp = fopen ( "note.xml" , "r" ) ;
while ( $data = fread ( $fp , 4096 ) ) {
// parse XML data
xml_parse ( $parser , $data , feof ( $fp ) ) or
die ( sprintf ( "XML error: %s on line %d" ,
xml_error_string ( xml_get_error_code ( $parser ) ) ,
xml_get_current_line_number ( $parser ) ) ) ;
}
xml_parser_free ( $parser ) ;
fclose ( $fp ) ;
?>
Run the instance
Use the same XML file, but display the XML data in another way:
<?php
$parser = xml_parser_create ( ) ;
function 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 stop ( $parser , $element_name ) {
echo "<br>" ;
}
function char ( $parser , $data ) {
echo $data ;
}
xml_set_element_handler ( $parser , "start" , "stop" ) ;
xml_set_character_data_handler ( $parser , "char" ) ;
$fp = fopen ( "note.xml" , "r" ) ;
while ( $data = fread ( $fp , 4096 ) ) {
xml_parse ( $parser , $data , feof ( $fp ) ) or
die ( sprintf ( "XML error: %s on line %d" ,
xml_error_string ( xml_get_error_code ( $parser ) ) ,
xml_get_current_line_number ( $parser ) ) ) ;
}
xml_parser_free ( $parser ) ;
fclose ( $fp ) ;
?>
Run the instance
xml_parse ( parser , data , end )
| parameter | describe |
|---|---|
| parser | Required. Specify the XML parser to use |
| data | Required. Specifies the data to parse. |
| end | Optional. If set to TRUE, the data in the data parameter is the last piece of data sent in this parsing. Note: Entity errors will be reported at the end of parsing - and will only be displayed if the end parameter is TRUE. |