Page 336 - Open Soource Technologies 304.indd
P. 336
Web Technologies-I
Notes XML_ERROR_INCORRECT_ENCODING
XML_ERROR_UNCLOSED_CDATA_SECTION
XML_ERROR_EXTERNAL_ENTITY_HANDLING
The constants generally are not much use. Use xml_error_string( ) to turn an error code into a
string that you can use when you report the error:
$message = xml_error_string(code);
For example:
$err = xml_get_error_code($parser); if ($err != XML_ERROR_NONE) die(xml_error_string($err));
13.4.6 Methods as Handlers
Because functions and variables are global in PHP, any component of an application that requires
several functions and variables is a candidate for object orientation. XML parsing typically
requires you to keep track of where you are in the parsing (e.g., “just saw an opening title
element, so keep track of character data until you see a closing title element”) with variables,
and of course you must write several handler functions to manipulate the state and actually do
something. Wrapping these functions and variables into a class provides a way to keep them
separate from the rest of your program and easily reuse the functionality later.
Use the xml_set_object( ) function to register an object with a parser. After you do so, the XML
parser looks for the handlers as methods on that object, rather than as global functions:
xml_set_object(object);
13.4.7 Sample Parsing Application
Let us develop a program to parse an XML file and display different types of information from
it. The XML file, given in example, contains information on a set of books.
Books.xml file
<?xml version=”1.0” ?>
<library>
<book>
<title>Programming PHP</title>
<authors> <author>ABC</author>
<author>XYZ</author>
</authors>
<isbn>1-xxxx0-2</isbn>
<comment>A great book!</comment></book>
<book>
<title>PHP Pocket Reference</title>
<authors> <author>ABC</author>
</authors>
<isbn>1-xxxx0-2</isbn>
330 LOVELY PROFESSIONAL UNIVERSITY