Php Tutorial xml processing (using xml_parser_create to parse, read, and generate)
Php has an xml_parser_create () function for processing xml documents. Let's take a look at this function.
The xml_parser_create () function creates an XML parser.
This function creates a new XML parser and returns the resource handle that can be used by other XML functions.
Syntax
Xml_parser_create (encoding) parameter description
Optional. Specify output encoding
<? Php
Function cdata_handler ($ parser, $ data ){
Print ($ data );
}
$ Xml = "<para> some character data </para> ";
$ Parser = xml_parser_create ();
Xml_set_character_data_handler ($ parser, 'cdata _ handler ');
If (xml_parse ($ parser, $ xml, true ))
Print ("Your XML document is well-formed .");
Else
Print ("Your XML document is not well-formed .");
Xml_parser_free ($ parser );
?>
Instance 2
Php
$ I = 1;
Function default_handler ($ p, $ data)
{
Global $ I;
Print ("$ I: default: $ datan ");
$ I ++;
}
Function cdata_handler ($ p, $ data)
{
Global $ I;
Print ("$ I: cdata: $ datan ");
$ I ++;
}
$ Xml = "<foo> bar </foo> <? Exec command?> ";
$ P = xml_parser_create ();
Xml_set_default_handler ($ p, 'default _ handler ');
Xml_set_character_data_handler ($ p, 'data _ handler ');
If (! Xml_parse ($ p, $ xml, true )){
Die (sprintf ("<br/> Parse error in <code> % s </code> (% s )",
Htmlspecialchars ($ xml ),
Xml_error_string (xml_get_error_code ($ p ))));
}
Xml_parser_free ($ p );
?>
3.
<? Php
Function pi_handler ($ p, $ target, $ data ){
Print ($ target );
Print ($ data );
}
$ Xml = "<? Exec ls-l/var?> <RootElement/> ";
$ P = xml_parser_create ();
Xml_set_processing_instruction_handler ($ p, 'pi _ handler ');
If (! Xml_parse ($ p, $ xml, true ))
Die (sprintf ("Parse error in <code> % s </code> (% s )",
Htmlspecialchars ($ xml ),
Xml_error_string (xml_get_error_code ($ p ))));
Else
Print ("XML processing complete. n ");
Xml_parser_free ($ p );
?>
Description
The optional parameter encoding is used in PHP 4 to specify the encoding method of the XML input to be parsed.
PHP 5 starts and automatically detects the input XML encoding. Therefore, the encoding parameter is only used to specify the encoding of the parsed output data.
In PHP 4, the default output encoding is the same as the input data encoding. If an empty string is passed, the parser attempts to search for the first 3 or 4 bytes to determine the document encoding.
In PHP 5.0.0 and 5.0.1, the default output character encoding is ISO-8859-1, while PHP 5.0.2 and later are UTF-8.
The parser supports ISO-8859-1, UTF-8, and US-ASCII encoding.