PHP xml_parse() Function
In this chapter you will learn:
- Description for PHP xml_parse() Function
- Syntax for PHP xml_parse() Function
- Parameter for PHP xml_parse() Function
- Return for PHP xml_parse() Function
- XML File used in later example
- Example - Parse xml data
- Example - Action methods for start and end tags
Description
The xml_parse() function parses an XML document.
Syntax
PHP xml_parse() Function has the following syntax.
xml_parse(parser,xml,end)
Parameter
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. |
Return
This function returns TRUE on success, or FALSE on failure.
XML File
test.xml XML File
<?xml version="1.0" encoding="ISO-8859-1"?>
<books>//ja v a 2 s .c o m
<name>PHP</name>
<name>Java</name>
</note>
Example 1
Parse xml data
<?php/*j a va 2 s . c o m*/
$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);
?>
Example 2
Action methods for start and end tags
<?php/*from j a v a 2 s .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);
?>
Next chapter...
What you will learn in the next chapter:
- Description for PHP xml_parse_into_struct() Function
- Syntax for PHP xml_parse_into_struct() Function
- Parameter for PHP xml_parse_into_struct() Function
- Return for PHP xml_parse_into_struct() Function
- Example - parses XML data into an array
Home » PHP Tutorial » PHP XML Functions