05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

characters outside the target encoding’s character range are demoted by replacing<br />

them with a question mark character (?).<br />

Use the constant XML_OPTION_TARGET_ENCODING to get or set the encoding of the text<br />

passed to callbacks. Allowable values are: "ISO-8859-1" (the default), "US-ASCII",<br />

and "UTF-8".<br />

Case folding<br />

By default, element and attribute names in XML documents are converted to all<br />

uppercase. You can turn off this behavior (and get case-sensitive element names) by<br />

setting the XML_OPTION_CASE_FOLDING option to false with the xml_parser_set_<br />

option( ) function:<br />

xml_parser_set_option(XML_OPTION_CASE_FOLDING, false);<br />

Using the Parser<br />

To use the XML parser, create a parser with xml_parser_create( ), set handlers and<br />

options on the parser, then hand chunks of data to the parser with the xml_parse( )<br />

function until either the data runs out or the parser returns an error. Once the processing<br />

is complete, free the parser by calling xml_parser_free( ).<br />

The xml_parser_create( ) function returns an XML parser:<br />

$parser = xml_parser_create([encoding]);<br />

The optional encoding parameter specifies the text encoding ("ISO-8859-1", "US-<br />

ASCII", or "UTF-8") of the file being parsed.<br />

The xml_parse( ) function returns TRUE if the parse was successful or FALSE if it was<br />

not:<br />

$success = xml_parse(parser, data [, final ]);<br />

The data argument is a string of XML to process. The optional final parameter<br />

should be true for the last piece of data to be parsed.<br />

To easily deal with nested documents, write functions that create the parser and set<br />

its options and handlers for you. This puts the options and handler settings in one<br />

place, rather than duplicating them in the external entity reference handler.<br />

Example 11-8 has such a function.<br />

Example 11-8. Creating a parser<br />

function create_parser ($filename) {<br />

$fp = fopen('filename', 'r');<br />

$parser = xml_parser_create( );<br />

xml_set_element_handler($parser, 'start_element', 'end_element');<br />

xml_set_character_data_handler($parser, 'character_data');<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.<br />

Parsing XML | 271

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!