The XMLReader::setRelaxNGSchema() function is an inbuilt function in PHP which is used to set the filename or URI for the RelaxNG Schema to use for validation.
Syntax:
bool XMLReader::setRelaxNGSchema( string $filename )
Parameters: This function accepts a single parameter $filename which holds the filename or URI pointing to a RelaxNG Schema.
Return Value: This function returns TRUE on success or FALSE on failure.
Below examples illustrate the XMLReader::setRelaxNGSchema() function in PHP:
-
Example 1:
- data.xml ( The XML file to be validated )
<?xmlversion="1.0"?><body>Â Â Â Â<div>Â Â Â Â Â Â Â Â<h1>Heading 1</h1>Â Â Â Â Â Â Â Â<h2>Heading 2</h2>Â Â Â Â</div>Â Â Â Â<div>Â Â Â Â Â Â Â Â<h1>Heading 3</h1>Â Â Â Â Â Â Â Â<h2>Heading 4</h2>Â Â Â Â</div></body> - rule.rng ( The rules to be followed by the XML file )
<elementname="body"ÂÂ Â<zeroOrMore>Â Â Â Â<elementname="div">Â Â Â Â Â Â<elementname="h1">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â Â Â<elementname="h2">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â</element>Â Â</zeroOrMore></element> - index.php ( PHP script to run the validator )
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Open the XML file$XMLReader->open('data.xml');ÂÂ// Load the rule file$XMLReader->setRelaxNGSchema('rule.rng');ÂÂ// Iterate through the XML nodes// and validate each nodewhile($XMLReader->read()) {   Âif($XMLReader->nodeType == XMLREADER::ELEMENT) {       Â// Check if XML follows the relaxNG rule       Âif($XMLReader->isValid()) {           Âecho"This document is valid!<br>";       Â}   Â}}?> - Output:
This document is valid! This document is valid! This document is valid! This document is valid! This document is valid! This document is valid! This document is valid!
Program 2:
- data.xml
<?xmlversion="1.0"?><body>Â Â Â Â<div>Â Â Â Â Â Â Â Â<!--Remove Heading 1Â Â Â Â Â Â Â Â Â Âto violate rule-->Â Â Â Â Â Â Â Â<h2>Heading 2</h2>Â Â Â Â</div>Â Â Â Â<div>Â Â Â Â Â Â Â Â<h1>Heading 3</h1>Â Â Â Â Â Â Â Â<h2>Heading 4</h2>Â Â Â Â</div></body> - rule.rng
<elementname="body"Â Â<zeroOrMore>Â Â Â Â<elementname="div">Â Â Â Â Â Â<elementname="h1">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â Â Â<elementname="h2">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â</element>Â Â</zeroOrMore></element> - index.php
<?phpÂÂ// Create a new XMLReader instance$XMLReader=newXMLReader();ÂÂ// Open the XML file$XMLReader->open('data.xml');ÂÂ// Load the rule file$XMLReader->setRelaxNGSchema('rule.rng');ÂÂ// Iterate through the XML nodeswhile($XMLReader->read()) {   Âif($XMLReader->nodeType == XMLREADER::ELEMENT) {       Â// Check if XML follows the relaxNG rule       Âif(!$XMLReader->isValid()) {           Âecho"This document is not valid!<br>";       Â}   Â}}?> - Output:
This document is not valid! This document is not valid! This document is not valid! This document is not valid!
Reference: https://www.php.net/manual/en/xmlreader.setrelaxngschema.php
