5

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();
}
1
  • What is the message of the fatal error? Commented Aug 28, 2011 at 18:24

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.