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)
{
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;
}
}
Comments
by Matthias Willerich on January 29 2008, 06:15 #
by Chris on May 25 2008, 20:13 #