PHP | DOMDocument schemaValidateSource() Function
Last Updated :
20 Feb, 2020
Improve
The DOMDocument::schemaValidateSource() function is an inbuilt function in PHP which is used to validate a document based on a schema defined in the given string. The difference between schemaValidate() and schemaValidateSource() is that the former accepts a schema filename whereas latter can accept a schema as string.
Syntax:
php
Output:
php
Output:
bool DOMDocument::schemaValidateSource( string $source, int $flags = 0 )Parameters: This function accept two parameters as mentioned above and described below:
- $source: It specifies the string containing the schema.
- $flags (Optional): It specifies the validation flags.
<?php
// Create a new DOMDocument
$doc = new DOMDocument;
// XSD schema
$XSD = "<?xml version=\"1.0\"?>
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"
elementFormDefault=\"qualified\">
<xs:element name=\"body\">
<xs:complexType>
<xs:sequence>
<xs:element name=\"h1\" type=\"xs:string\"/>
<xs:element name=\"strong\" type=\"xs:integer\"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
// Load the XML
$doc->loadXML("<?xml version=\"1.0\"?>
<body>
<h1> Hello </h1>
<strong> 22 </strong>
</body>");
// Check if XML follows the schema rule
if ($doc->schemaValidateSource($XSD)) {
echo "This document is valid!\n";
}
?>
<?php
// Create a new DOMDocument
$doc = new DOMDocument;
// XSD schema
$XSD = "<?xml version=\"1.0\"?>
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"
elementFormDefault=\"qualified\">
<xs:element name=\"body\">
<xs:complexType>
<xs:sequence>
<xs:element name=\"h1\" type=\"xs:string\"/>
<xs:element name=\"strong\" type=\"xs:integer\"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
// Load the XML
$doc->loadXML("<?xml version=\"1.0\"?>
<body>
<h1> Hello </h1>
<strong> 22 </strong>
</body>");
// Check if XML follows the schema rule
if ($doc->schemaValidateSource($XSD)) {
echo "This document is valid!\n";
}
?>
This document is valid!Program 2:
<?php
// Create a new DOMDocument
$doc = new DOMDocument;
// RNG schema
$XSD = "<?xml version=\"1.0\"?>
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"
elementFormDefault=\"qualified\">
<xs:element name=\"student\">
<xs:complexType>
<xs:sequence>
<xs:element name=\"name\" type=\"xs:string\"/>
<xs:element name=\"rollno\" type=\"xs:integer\"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>";
// Load the XML
$doc->loadXML("<?xml version=\"1.0\"?>
<student>
<!-- rollnow element is missing here -->
<name> XYZ </name>
</student>
");
// Check if XML follows the relaxNG rule
if (!$doc->schemaValidateSource($XSD)) {
echo "This document is not valid!\n";
}
?>
This document is not valid!Reference: https://www.php.net/manual/en/domdocument.schemavalidatesource.php