In his previous comment, Mike A wrote about validating documents using an XSD. However, you can validate without one. In my case, I needed to ensure that the content entered was just valid XML or not, and I couldn't find an XSD to support that. So I wrote this:
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;
}
The catch here is that the function only checks for the first error is LIBXML_ERR_FATAL, which would break XSL/XML compilation.
In my experience, the errors are returned by libxml_get_errors in descending severity, so this may be an OK thing to do.