Search code examples
xmlxsdxmlreaderlibxml2xml-libxml

validate XML against XSD with errors


I want to validate XML against XSD file and get errors if there is any.

It works fine when I use it with DOM but not XMLReader. As far as know they both use libxml library so I tried to use it for XMLReader but no luck.

Thanks

DOM (Works fine)

libxml_use_internal_errors(true);

if (! $xml->schemaValidate($xsd_file))
{
    get_errors();
    exit;
}

function get_errors()
{
    $messages   = null;
    $errors     = libxml_get_errors();

    foreach ($errors as $error)
    {
        switch ($error->level)
        {
            case LIBXML_ERR_ERROR:
                $messages .= 'Error ' . $error->code . $error->message;
                break;

            case LIBXML_ERR_WARNING:
                $messages .= 'Warning ' . $error->code . $error->message;
                break;

            case LIBXML_ERR_FATAL:
                $messages .= 'Fatal ' . $error->code . $error->message;
                break;
        }

        echo $messages .= ($error->file) ? $error->file : $error->line;
    }
}

XMLREADER (Doesn't work with the same error function above)

libxml_use_internal_errors(true);

//This returns true all times whether XML has faults or not
if (! $reader->setSchema($xsd_file))
{
   //This echos nothing whether XML has faults or not
   get_errors();
}

Solution

  • After you set the schema, I don't see any read() or isValid() going on, so how would you get the errors? Take a look at the documentation (I assume PHP), it should help you get an idea.