Page 334 - Open Soource Technologies 304.indd
P. 334
Web Technologies-I
Notes The xml_parser_create( ) function returns an XML parser:
$parser = xml_parser_create([encoding]);
The optional encoding parameter specifies the text encoding (“ISO-8859-1”, “US-ASCII”, or
“UTF-8”) of the file being parsed.
The xml_parse( ) function returns TRUE if the parse was successful or FALSE if it was not:
$success = xml_parse(parser, data [, final ]);
The data argument is a string of XML to process. The optional final parameter should be true
for the last piece of data to be parsed.
To easily deal with nested documents, write functions that create the parser and set its options and
handlers for you. This puts the options and handler settings in one place, rather than duplicating
them in the external entity reference handler. Example has such a function is as follows.
Creating a parser.
function create_parser ($filename) {
$fp = fopen(‘filename’, ‘r’);
$parser = xml_parser_create( );
xml_set_element_handler($parser, ‘start_element’, ‘end_element’);
xml_set_character_data_handler($parser, ‘character_data’);
xml_set_processing_instruction_handler($parser, ‘processing_instruction’);
xml_set_default_handler($parser, ‘default’);
return array($parser, $fp);
}
function parse ($parser, $fp) {
$blockSize = 4 * 1024; // read in 4 KB chunks
while($data = fread($fp, $blockSize)) { // read in 4 KB chunks
if(!xml_parse($parser, $data, feof($fp))) {
// an error occurred; tell the user where
echo ‘Parse error: ‘ . xml_error_string($parser) . “ at line “ .
xml_get_current_line_number($parser));
return FALSE;
}
}
328 LOVELY PROFESSIONAL UNIVERSITY