Thursday, November 20, 2025
HomeLanguagesPHP | DOMDocument schemaValidateSource() Function

PHP | DOMDocument schemaValidateSource() Function

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

RELATED ARTICLES

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6778 POSTS0 COMMENTS
Nicole Veronica
11927 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6905 POSTS0 COMMENTS
Ted Musemwa
7162 POSTS0 COMMENTS
Thapelo Manthata
6861 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS