The xml_parse() function parses an XML document.
PHP xml_parse() Function has the following syntax.
xml_parse(parser,xml,end)
Parameter | Is Required | Description |
---|---|---|
parser | Required. | XML parser to use |
xml | Required. | XML data to parse |
end | Optional. | If this parameter is TRUE, the data in the "xml" parameter is the last piece of data sent in this parse. |
This function returns TRUE on success, or FALSE on failure.
test.xml XML File
<?xml version="1.0" encoding="ISO-8859-1"?> <books> <name>PHP</name> <name>Java</name> </note>
Parse xml data
<?php/*from w w w.ja va 2 s . com*/
$parser=xml_parser_create();
function char($parser,$data){
echo $data;
}
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");
while ($data=fread($fp,1024)){
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)));
}
xml_parser_free($parser);
?>
Action methods for start and end tags
<?php/*from w w w . ja va2s . com*/
$parser=xml_parser_create();
function start($parser,$element_name,$element_attrs){
switch($element_name){
case "name":
echo "name\n";
break;
case "books":
echo "books\n";
break;
}
}
function stop($parser,$element_name){
echo "\n";
}
function char($parser,$data){
echo $data;
}
xml_set_element_handler($parser,"start","stop");
xml_set_character_data_handler($parser,"char");
$fp=fopen("test.xml","r");
while ($data=fread($fp,1024)){
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)));
}
xml_parser_free($parser);
?>