registerXPathNamespace("xs","http://www.w3.org/2001/…" name="description"> registerXPathNamespace("xs","http://www.w3.org/2001/…" property="og:description">

Blog : Is it possible to validate XML against multiple schemas in PHP?

Is it possible to validate XML against multiple schemas in PHP?


<code>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)</code>

But it is possible only thanks to the fact that the schemas are the same - i.e.

<code><xs:schemaxmlns="NAMESPACE"targetNamespace="NAMESPACE"xmlns:xs="http://www.w3.org/2001/XMLSchema"elementFormDefault="qualified"attributeFormDefault="unqualified"></code>

is in both files.
   

     

   

Syfmony2 developers solved that problem. It's not freakin' clean but will do:

<code>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:importnamespace="http://www.w3.org/XML/1998/namespace"/>
$imports
</xsd:schema>
EOF
  ;

  $current = libxml_use_internal_errors(true);
  $valid = $dom->schemaValidateSource($source);</code>