PHP Check if XML String is Valid

Posted on March 17, 2019 at 12:14 pm

Simple PHP function to check if a XML string is valid:

function isValidXML($xml)
{
    libxml_use_internal_errors(true);
 
    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML($xml);
 
    $errors = libxml_get_errors();
 
    libxml_clear_errors();
 
    if(empty($errors)){
        return array("valid" => true);
    }
 
    $error = $errors[0];
 
    if($error->level < 3){
        return array("valid" => true);
    }
 
    $explodedxml = explode("r", $xml);
    $badxml = $explodedxml[($error->line)-1];
 
    $message = $error->message . ' at line ' . $error->line;
 
    return array("valid" => false, "message" => $message, "badxml" => htmlentities($badxml), "xml" => htmlentities($xml));
}

You can use this function before calling SimpleXMLElement().

So the PHP script would not crash in case of errors:

$xml = "...";
 
$xmlvalid = isValidXML($xml);
 
if($xmlvalid['valid'] == true)
{
    $data = new SimpleXMLElement($xml);
    ...
}
else
{
    // Save error message $xmlvalid['message'] somewhere?
}

Alternatively you can suppress XML errors and warnings:

$data = new SimpleXMLElement($xml, LIBXML_NOERROR | LIBXML_NOWARNING, false);

References:

http://php.net/manual/en/class.simplexmlelement.php#107869
http://php.net/manual/en/class.simplexmlelement.php
http://php.net/manual/en/function.libxml-get-errors.php
http://php.net/manual/en/function.libxml-get-last-error.php
http://php.net/manual/en/ref.libxml.php

Receive updates via email

Other Posts

Updated Posts