XML validation in PHP

by Pascal Opitz

published 8 November 2006

Working with user input that needs to be valid XML, it turns out that PHP5 has a built-in validation function.

For just checking if the XML is well-formed you can just leave the parameter with the filename of the xsd blank.

See the following example code for a possible application:

class XML
{
        public static function validate($xml)
        {
                libxml_use_internal_errors(true);

                $doc = new DOMDocument('1.0', 'utf-8');
                $doc->loadXML($xml);

                $errors = libxml_get_errors();
                if (empty($errors))
                {
                        return true;
                }

                $error = $errors[ 0 ];
                if ($error->level < 3)
                {
                        return true;
                }

                $lines = explode("r", $xml);
                $line = $lines[($error->line)-1];

                $message = $error->message.' at line '.$error->line.':<br />'.htmlentities($line);

                return $message;
        }
}

Comment

  1. I just started using this (using $doc->schemaValidate, though) to validate xml output with simpletest, and it passes and fails where expected. Sweet!
    Matthias Willerich    29 January, 12:15pm    #
  2. The link given above is outdated; see DOMDocument::schemaValidate
    — Chris    26 May, 2:13am    #

Have your say

If your comment doesn't show up straight away, please don't be offended - we're not censoring, we are just trying to keep out all the viagra and poker ads. Thanks to an explosion of spam all comments are held for manual green-lighting.

name Remember
email
http://
Message <?>

Quick links

Other people's articles that we think you might be interested in: