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

jspeshu picture jspeshu · Dec 29, 2010 · Viewed 74.8k times · Source

i was trying to check the validity of a string as xml using this simplexml_load_string()Docs function but it displays a lot of warning messages.

How can I check whether a string is a valid XML without suppressing (@ at the beginning) the error and displaying a warning function that expec

Answer

Tjirp picture Tjirp · Dec 29, 2010

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();
}