I have a xml called sample.xml
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
and sample.xsd to validate sample.xml
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
I’m trying to validate sample.xml through my php code and since there are no namespaces in sample.xml I’m adding the namespace from the php code.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
$file = 'sample.xml';
$schema = 'sample.xsd';
$doc = new DOMDocument();
$doc->load($file);
$doc->createAttributeNS('http://www.w3schools.com', 'xmlns');
$doc->createAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsi');
$doc->createAttributeNS('http://www.w3schools.com sample.xsd', 'xsi:schemaLocation');
print $doc->saveXML();
if ($doc->schemaValidate($schema)) {
print "$file is valid.\n";
} else {
print "$file is invalid.\n";
}
?>
and when I run the code I get the following error
Fatal error: Uncaught exception ‘DOMException’ with message ‘Namespace
Error’ in /var/www/xsd/test_sample.php:20 Stack trace: #0
/var/www/xsd/test_sample.php(20):
DOMDocument->createAttributeNS(‘http://www.w3.o…’, ‘xmlns:xsi’) #1
{main} thrown in /var/www/xsd/test_sample.php on line 20
if I comment out the line $doc->createAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xmlns:xsi'); the code runs fine but then I’m not able to validate the xml as it says sample.xml is invalid
Can some one help me with this code?
First thing I would fix would be to also use appendChild on your document element. Without that, the attribute is created but not appended to your tree.
For validation, please take a look at this link.