XML validation in PHP
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
- 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 # - The link given above is outdated; see DOMDocument::schemaValidate
— Chris 26 May, 2:13am #
Quick links
Other people's articles that we think you might be interested in:
- Ajaxian » Web Inspector: Looking good, and profiling nicely
- smush it!
- cssdoc - Trac
- CSS Systems for writing maintainable CSS | Natalie Downe
- The PNG Gamma Dilemma - Trevor Morris Photographics
Want to buy a cheap laptop for your design work? read laptop reviews at laptopical.com