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.

[source language=“php“]
/**
* 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 );
}
[/source]

4 Kommentare zu „Check for Valid XML with PHP

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

Antworte auf den Kommentar von davidAntwort abbrechen