PHP | DOMDocument relaxNGValidate() Function

The DOMDocument::relaxNGValidate() function is an inbuilt function in PHP which is used to performs relaxNG validation on the document. The relaxNG is an alternative to DDT and defines a structure which needs to be followed by the XML document.
Syntax:
bool DOMDocument::relaxNGValidate( string $filename )
Parameters: This function accepts a single parameter $filename which holds the RNG file.
Return Value: This function returns TRUE on success or FALSE on failure.
Below given programs illustrate the DOMDocument::relaxNGValidate() function in PHP:
Program 1:
- File name: rule.rng
<element name="college"ÂÂ Â<zeroOrMore>Â Â Â Â<element name="rollno">Â Â Â Â Â Â<element name="name">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â Â Â<element name="subject">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â</element>Â Â</zeroOrMore></element> - File name: index.php
<?phpÂÂ// Create a new DOMDocument$doc=newDOMDocument;ÂÂ// Load the XML$doc->loadXML("<?xml version=\"1.0\"?><college>Â Â<rollno>Â Â Â Â<name>John Smith</name>Â Â Â Â<subject>Web</subject>Â Â</rollno>Â Â<rollno>Â Â Â Â<name>John Doe</name>Â Â Â Â<subject>CSE</subject>Â Â</rollno></college>");ÂÂ// Check if XML follows the relaxNG ruleif($doc->relaxNGValidate('rule.rng')) {Â Â Â Âecho"This document is valid!\n";}?> - Output:
This document is valid!
Program 2:
- File name: rule.rng
<element name="company"ÂÂ Â<zeroOrMore>Â Â Â Â<element name="employee">Â Â Â Â Â Â<element name="name">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â Â Â<element name="salary">Â Â Â Â Â Â Â Â<text/>Â Â Â Â Â Â</element>Â Â Â Â</element>Â Â</zeroOrMore></element> - File name: index.php
<?phpÂÂ// Create a new DOMDocument$doc=newDOMDocument;ÂÂ// Load the XML$doc->loadXML("<?xml version=\"1.0\"?><company>Â Â<employee>Â Â Â Â<name>John Smith</name>Â Â Â Â<salary>Web</salary>Â Â</employee>Â Â<employee>Â Â Â Â<!-- Do not add salary to voilate rule -->Â Â Â Â<name>John Doe</name>Â Â</employee></company>");ÂÂ// Check if XML doesn't follows the relaxNG ruleif(!$doc->relaxNGValidate('rule.rng')) {Â Â Â Âecho"This document is not valid!\n";}?> - Output:
This document is not valid!
Reference: https://www.php.net/manual/en/domdocument.relaxngvalidate.php



