PHP | DOMDocument schemaValidateSource() Function

Last Updated : 20 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Report
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:
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.
Return Value: This function returns TRUE on success or FALSE on failure. Below given programs illustrate the DOMDocument::schemaValidateSource() function in PHP: Program 1: php
<?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";
}
?>
Output:
This document is valid!
Program 2: php
<?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";
}
?>
Output:
This document is not valid!
Reference: https://www.php.net/manual/en/domdocument.schemavalidatesource.php

Next Article

Similar Reads