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
$doc = new DOMDocument;
$XSD = "<?xml version=\"1.0\"?>
<xs:schema xmlns:xs=\"http:
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>";
$doc ->loadXML("<?xml version=\"1.0\"?>
<body>
<h1> Hello </h1>
<strong> 22 </strong>
</body>");
if ( $doc ->schemaValidateSource( $XSD )) {
echo "This document is valid!\n" ;
}
?>
|
Output:
This document is valid!
Program 2:
<?php
$doc = new DOMDocument;
$XSD = "<?xml version=\"1.0\"?>
<xs:schema xmlns:xs=\"http:
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>";
$doc ->loadXML("<?xml version=\"1.0\"?>
<student>
<!-- rollnow element is missing here -->
<name> XYZ </name>
</student>
");
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
Last Updated :
20 Feb, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...