How check if a String is a Valid XML with-out Displaying a Warning in PHP
Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.
libxml_use_internal_errors(true);$doc = simplexml_load_string($xmlstr);$xml = explode("\n", $xmlstr);if (!$doc) { $errors = libxml_get_errors(); foreach ($errors as $error) { echo display_xml_error($error, $xml); } libxml_clear_errors();}
From the documentation:
Dealing with XML errors when loading documents is a very simple task. Using the
libxml
functionality it is possible to suppress all XML errors when loading the document and then iterate over the errors.The
libXMLError
object, returned bylibxml_get_errors()
, contains several properties including themessage
,line
andcolumn
(position) of the error.
libxml_use_internal_errors(true);$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");if (!$sxe) { echo "Failed loading XML\n"; foreach(libxml_get_errors() as $error) { echo "\t", $error->message; }}
Reference: libxml_use_internal_errors