How check if a String is a Valid XML with-out Displaying a Warning in PHP How check if a String is a Valid XML with-out Displaying a Warning in PHP xml xml

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.

Simple XML loading string

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 by libxml_get_errors(), contains several properties including the message, line and column (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


try this one

//check if xml is valid documentpublic function _isValidXML($xml) {    $doc = @simplexml_load_string($xml);    if ($doc) {        return true; //this is valid    } else {        return false; //this is not valid    }}