Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP XML Validation Throws Fatal Exceptions When Passed Bad XML

I've a quick function to load up an XML string, and validate it against a schema. When its given well formed XML, it behaves perfectly.

However when I muck up the xml syntax itself, php throws a fatal error and kills the script. I am checking the loadXML function return value, and I want a simple true/false. If the xml is dirty, loadXML() will fail and I can simply return validation failure. I've tried setting an empty error handler, but it still kills the script.

Any ideas? Do I need to downgrade errors or something?

Included code for reference (PHP):

function __maskerrors(){};

function ValidateImageXML($xml_string)
{
    /* Parse XML data string into DOM object */
    $xdoc = new DomDocument;

    /* Calculate schema location */
    $schema = dirname(realpath(__FILE__));
    $schema.= "/image-xml-schema.xsd";

    /* Mask any errors */
    set_error_handler('__maskerrors');

    /* Parse xml string, check for success */
    if($xdoc->loadXML($xml_string))
    {
        /* Validate xml against schema */
        if($xdoc->schemaValidate($schema))
        {
            /* Valid XML structure & valid against schema, return true */
            return true;
        }
        else
        {
            /* Valid XML structure, but invalid against schema. Return false */
            return false;
        }
    }
    else
    {
        /* Invalid XML structure, return false */
        return false;
    }

    /* Stop masking errors */
    restore_error_handler();
}
like image 979
Oliver Avatar asked Oct 10 '22 03:10

Oliver


1 Answers

Try with

libxml_use_internal_errors(true);
$xdoc->loadXml($yourXml);
libxml_clear_errors();
return $xdoc->schemaValidate($schema)

This will disable libxml errors and allow user to fetch error information as needed (or clear them)

See http://.php.net/manual/en/book.libxml.php

like image 139
Gordon Avatar answered Oct 17 '22 22:10

Gordon