PHP | XMLReader setSchema() Function

The XMLReader::setSchema() function is an inbuilt function in PHP which is used to validate the document using a XSD schema. This XSD schema is nothing but a file that defines the rule for the XML structure and should be in the form of .xsd file.
Syntax:
bool XMLReader::setSchema( string $filename )
Parameters: This function accepts a single parameter $filename which holds the XSD filename.
Return Value: This function returns TRUE on success or FALSE on failure.
Exceptions: This function throws E_WARNING if libxml extension was compiled without schema support.
Below examples illustrate the XMLReader::setSchema() function in PHP:
Example 1:
- data.xml ( The XML file to be validated )
<?xmlversion="1.0"?><student><name>Rahul</name><rollno>1726262</rollno></student> - rule.xsd ( The rules to be followed by the XML file )
<?xmlversion="1.0"?><xs:schemaxmlns:xs=elementFormDefault="qualified"><xs:elementname="student"><xs:complexType><xs:sequence><xs:elementname="name"type="xs:string"/><xs:elementname="rollno"type="xs:integer"/></xs:sequence></xs:complexType></xs:element></xs:schema> - index.php ( The PHP script to run the validation )
<?php// Create a new XMLReader instance$XMLReader=newXMLReader();// Open the XML file$XMLReader->open('data.xml');// Load the rule$XMLReader->setSchema('rule.xsd');// Iterate through the XML nodeswhile($XMLReader->read()) {if($XMLReader->nodeType == XMLREADER::ELEMENT) {// Check if XML follows the XSD ruleif($XMLReader->isValid()) {echo"This document is valid!<br>";}}}?> - Output:
This document is valid! This document is valid! This document is valid!
Example 2:
- data.xml
<?xmlversion="1.0"?><div><phoneNo>This should not be text</phoneNo></div> - rule.xsd
<?xmlversion="1.0"?><xs:schemaxmlns:xs=elementFormDefault="qualified"><xs:elementname="div"><xs:complexType><xs:sequence><xs:elementname="phoneNo"type="xs:integer"/></xs:sequence></xs:complexType></xs:element></xs:schema> - index.php
<?php// Create a new XMLReader instance$XMLReader=newXMLReader();// Open the XML file$XMLReader->open('data.xml');// Load the rule$XMLReader->setSchema('rule.xsd');// Iterate through the XML nodeswhile($XMLReader->read()) {if($XMLReader->nodeType == XMLREADER::ELEMENT) {// Check if XML follows the XSD ruleif(!$XMLReader->isValid()) {echo"This document is not valid!<br>";}}}?> - Output:
This document is not valid! This document is not valid!
Reference: https://www.php.net/manual/en/xmlreader.setschema.php



