xmlsimplexmlphplibxml2

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


i was trying to check the validity of a string as xml using the 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 using @ at the beginning to suppress the errors and warnings?


Solution

  • 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 !== false) {
        $errors = libxml_get_errors();
    
        foreach ($errors as $error) {
            // Display the error how you want here
            print_r($error);
        }
    
        libxml_clear_errors();
    }