Latest: Genstatic, my first sip of coffee

Content with Style

Web Technique

XML validation in PHP

by Pascal Opitz on November 8 2006, 06:41

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)

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

                $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;


  • I just started using this (using $doc->schemaValidate, though) to validate xml output with simpletest, and it passes and fails where expected. Sweet!

    by Matthias Willerich on January 29 2008, 06:15 - #

  • The link given above is outdated; see DOMDocument::schemaValidate

    by Chris on May 25 2008, 20:13 - #

Comments for this article are closed.