Is it possible to validate XML against multiple schemas in PHP?
I'm wondering if it is possible to validate xml against multiple schemas in PHP or I h开发者_JAVA百科ave to merge my schemas somehow.
Thanks for an answer!
The main schema file must contain an include tag for each child schema file. For example:
<xs:include schemaLocation="2nd_schema_file.xsd"/>
I've solved my problem via simple PHP script:
$mainSchemaFile = dirname(__FILE__) . "/main-schema.xml";
$additionalSchemaFile = 'second-schema.xml';
$additionalSchema = simplexml_load_file($additionalSchemaFile);
$additionalSchema->registerXPathNamespace("xs", "http://www.w3.org/2001/XMLSchema");
$nodes = $additionalSchema->xpath('/xs:schema/*');
$xml = '';
foreach ($nodes as $child) {
$xml .= $child->asXML() . "\n";
}
$result = str_replace("</xs:schema>", $xml . "</xs:schema>", file_get_contents($mainSchemaFile));
var_dump($result); // merged schema in form XML (string)
But it is possible only thanks to the fact that the schemas are the same - i.e.
<xs:schema xmlns="NAMESPACE"
targetNamespace="NAMESPACE"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
is in both files.
Syfmony2 developers solved that problem. It's not freakin' clean but will do:
function validateSchema(\DOMDocument $dom)
{
$tmpfiles = array();
$imports = '';
foreach ($this->schemaLocations as $namespace => $location) {
$parts = explode('/', $location);
if (preg_match('#^phar://#i', $location)) {
$tmpfile = tempnam(sys_get_temp_dir(), 'sf2');
if ($tmpfile) {
file_put_contents($tmpfile, file_get_contents($location));
$tmpfiles[] = $tmpfile;
$parts = explode('/', str_replace('\\', '/', $tmpfile));
}
}
$drive = '\\' === DIRECTORY_SEPARATOR ? array_shift($parts).'/' : '';
$location = 'file:///'.$drive.implode('/', array_map('rawurlencode', $parts));
$imports .= sprintf(' <xsd:import namespace="%s" schemaLocation="%s" />' . PHP_EOL, $namespace, $location);
}
$source = <<<EOF
<?xml version="1.0" encoding="utf-8" ?>
<xsd:schema xmlns="http://symfony.com/schema"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://symfony.com/schema"
elementFormDefault="qualified">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace"/>
$imports
</xsd:schema>
EOF
;
$current = libxml_use_internal_errors(true);
$valid = $dom->schemaValidateSource($source);
foreach ($tmpfiles as $tmpfile) {
@unlink($tmpfile);
}
if (!$valid) {
throw new \InvalidArgumentException(implode("\n", $this->getXmlErrors()));
}
libxml_use_internal_errors($current);
}
Considering that the DOMDocument::schemaValidate
method receives the path to the schema file as a parameter, I'd say that you just have to call that method several times : once for each one of your schemas.
See also DOMDocument::schemaValidateSource
if you have your schemas in PHP strings ; the idea (and the answer) will be the same, though : just call the method several times.
精彩评论