20.1 Error Handling


When errors occur, you want to know what happens, but the errors given by XML are usually in the form of constants such as XML_ERROR_SYNTAX . You would rather have the messages in plain English.

Technique

Here is a method of converting the error numbers into their corresponding error messages:

 <?php print xml_error_string(XML_ERROR_SYNTAX); ?> 

Comments

Given an error code, the xml_error_string() will return a text description. You can give the xml_error_string() function an error code by either passing it one of the predefined constants or, if you are parsing a document, by using the xml_get_ error_code() function like so

 <?php print xml_error_string(xml_get_error_code($parser)); ?> 

Note

Throughout the rest of this chapter, I will use the following to catch errors when xml_parse() fails:

 <?php die (sprintf ("XML Error: %s at line %d.",               xml_error_string (xml_get_error_code ($parser)),               xml_get_current_line_number ($parser))); ?> 

This will print out something like

 XML Error: Malformed Syntax at line 5. 

This error reporter is great for the small examples in this book, but if you are working on bigger projects, you might want to make the error output a little nicer. Here is an example of how you might do that:

 <?php function output_error($parser) {     $error_string = xml_error_string (xml_get_error_code ($parser));     $error_line = xml_get_current_line_number ($parser);     $error = "An <b>XML Error</b> occurred on line $line: $errstr\n";     error_log($error, 0);     print $error;     exit; } /* then call it */ output_error($parser); ?> 



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net