Function to validate an xml file
You can apply this function to a file. Say you have an xml file located at /home/foobar/myfile.xml and you want to validate it. The following function validate_xml() will do it. On success it returns TRUE and on failure it returns FALSE (1 and 0 respectively).
function validate_xml($xml_file)
{
$a_errors = array();
$xml_parser = xml_parser_create();
#####> open a file and read data
$fp = fopen($xml_file, 'r');
while($xml_data = fread($fp, 4096))
{
#####> parse the data chunk
if(!xml_parse($xml_parser,$xml_data,feof($fp)))
{
$a_errors[] = "Error: " . xml_error_string(xml_get_error_code($xml_parser));
}
}
fclose($fp);
xml_parser_free($xml_parser);
if(count($a_errors) == 0)
{
return 1;
}
else
{
return 0;
}
}
?>
Here is the syntax to validate /home/foobar/myfile.xml.
if(validate_xml("/home/foobar/myfile.xml"))
{
print("Your xml file is valid.");
}
else
{
print("Your xml file is not valid.");
}
?>
With a little modification, it also builds an array $a_errors[] that actually contains the errors it found in the xml. If you'd like to return the errors, anywhere it returns TRUE i.e. return 1; just replace that with return $a_errors;. You can than perform a check on that to see if there are more than 0 errors, and if so, it doesn't validate. You can also use the $a_errors[] to actually print the errors.
Here is the function that returns $a_errors[].
function validate_xml($xml_file)
{
$a_errors = array();
$xml_parser = xml_parser_create();
#####> open a file and read data
$fp = fopen($xml_file, 'r');
while($xml_data = fread($fp, 4096))
{
#####> parse the data chunk
if(!xml_parse($xml_parser,$xml_data,feof($fp)))
{
$a_errors[] = "Error: " . xml_error_string(xml_get_error_code($xml_parser));
}
}
fclose($fp);
xml_parser_free($xml_parser);
return $a_errors;
}
?>
I believe the root of these functions came from the W3 Schools » website.