Check for Valid XML with PHP

Simple function to check if XML is valid. It just loads the XML into DOMDocument and checks for errors.

*  Takes XML string and returns a boolean result where valid XML returns true
function is_valid_xml ( $xml ) {
    libxml_use_internal_errors( true );
    $doc = new DOMDocument('1.0', 'utf-8');
    $doc->loadXML( $xml );
    $errors = libxml_get_errors();
    return empty( $errors );

4 thoughts on “Check for Valid XML with PHP

  1. I prefer:
    @$xml = simplexml_load_string(‘Santa’);
    // Do something with xml object.
    $original = $xml->asXML();

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s