Validating XML files, including Google sitemap and atom XML using PHP
Posted on August 11th, 2010 in PHP | No Comments »
The following method is pulled from a class, in a php command line tool, that I created to generate google sitemap files and also Google Base atom files.
What I wanted to do was, vailidate the generated xml files against a schema, before saving them.
You can do this via the command using xmllint.
xmllint –schema atom.xsd.xml –valid –noout /xmlfiles/.test.xml.tmp
However you can easily do this in PHP.
static function validate_google_xml($xmlfile, $type)
{
print("Validating {$xmlfile} \n");
$xdoc = new DomDocument;
if($type == 'siteindex')
{
$schema = self::$scriptDir.'siteindex.xsd';
@$xdoc->Load($xmlfile);
if (@$xdoc->schemaValidate($schema))
{
return true;
}
}elseif($type == 'sitemap')
{
$schema = self::$scriptDir.'sitemap.xsd';
//echo $schema ; die;
@$xdoc->Load($xmlfile);
if (@$xdoc->schemaValidate($schema))
{
return true;
}
}elseif($type == 'atom')
{
$schema = self::$scriptDir.'atom.xsd.xml';
//echo $schema ; die;
@$xdoc->Load($xmlfile);
if (@$xdoc->schemaValidate($schema))
{
return true;
}
}
}