The DOMDocument::schemaValidate() function is an inbuilt function in PHP which is used to validate a document based on the given schema file. The schema file can be in an XSD format which is the recommendation from W3C (World Wide Web Consortium).
Syntax:
bool DOMDocument::schemaValidate( string $filename, int $flags = 0 )
Parameters: This function accept two parameters as mentioned above and described below:
- $filename: It specifies the path to 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::schemaValidate() function in PHP:
Program 1:
- File name: rule.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> - File name: index.php
<?phpÂÂ// Create a new DOMDocument$doc=newDOMDocument;ÂÂ// Load the XML$doc->loadXML("<?xml version=\"1.0\"?><student>Â Â Â Â<name>Rahul </name>Â Â Â Â<rollno>34</rollno></student>");ÂÂ// Check if XML follows the ruleif($doc->schemaValidate('rule.xsd')) {Â Â Â Âecho"This document is valid!\n";}?> - Output:
This document is valid!
Program 2:
- File name: rule.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> - File name: index.php
<?phpÂÂ// Create a new DOMDocument$doc=newDOMDocument;ÂÂ// Load the XML$doc->loadXML("<?xml version=\"1.0\"?><student>Â Â Â Â<h1>Rahul </h1></student>");ÂÂ// Check if XML follows the ruleif(!$doc->schemaValidate('rule.xsd')) {Â Â Â Âecho"This document is not valid!\n";}?> - Output:
This document is not valid!
Reference: https://www.php.net/manual/en/domdocument.schemavalidate.php
