How to validate XML in PHP
Snippet
The function libxml_get_errors returns an array with LibXMLError objects if there are any errors in the buffer, or an empty array otherwise.
1) via DOMDocument
<?php
/**
* @param string $xmlContent A well-formed XML string
* @param string $version 1.0
* @param string $encoding utf-8
* @return bool
*/
function isXMLContentValid($xmlContent, $version = '1.0', $encoding = 'utf-8'){
if (trim($xmlContent) == '') {
return false;
}
libxml_use_internal_errors(true);
$doc = new DOMDocument($version, $encoding);
$doc->loadXML($xmlContent);
$errors = libxml_get_errors();
libxml_clear_errors();
return empty($errors);
}
$xml = '<website><domain>wtools.io</domain><title>Online Web Tools</title></website>';
if(isXMLContentValid($xml)){
echo "Valid XML string";
} else {
echo "Not valid JSON string";
}
2) via simplexml_load_string
<?php
/**
* @param string $xmlContent A well-formed XML string
* @return bool
*/
function isXMLContentValid($xmlContent){
if (trim($xmlContent) == '') {
return false;
}
libxml_use_internal_errors(true);
$xml = simplexml_load_string($xmlContent);
if ($xml === false) {
return false;
} else {
return true;
}
}
$xml = '<website><domain>wtools.io</domain><title>Online Web Tools</title></website>';
if(isXMLContentValid($xml)){
echo "Valid XML string";
} else {
echo "Not valid JSON string";
}
If you want to validate XML online, then you can use our free tool.