PHP | DOMDocument relaxNGValidateSource() Function

The DOMDocument::relaxNGValidateSource() function is an inbuilt function in PHP which is used to perform relaxNG validation on the document using a string as RNG schema. The difference between relaxNGValidate() and relaxNGValidateSource() is that the former accepts a rng schema filename whereas latter can accept a rng schema as string too.Â
Syntax:
bool DOMDocument::relaxNGValidateSource( string $source )
Parameters: This function accepts a single parameter $source which holds the RNG schema.Â
Return Value: This function returns TRUE on success or FALSE on failure.Â
Below given programs illustrate the DOMDocument::relaxNGValidateSource() function in PHP:Â
Program 1:Â
php
<?phpÂ
// Create a new DOMDocument$doc = new DOMDocument;Â
// RNG schema$RNG = "<element name=\"body\" Â Â Â Â xmlns=\"http://relaxng.org/ns/structure/1.0\"><zeroOrMore>Â Â <element name=\"div\">Â Â Â Â <element name=\"h1\">Â Â Â Â Â Â <text/>Â Â Â Â </element>Â Â Â Â <element name=\"h2\">Â Â Â Â Â Â <text/>Â Â Â Â </element>Â Â </element></zeroOrMore></element>";Â
// Load the XML$doc->loadXML("<?xml version=\"1.0\"?><body>Â Â <div>Â Â Â Â <h1>Heading 1</h1>Â Â Â Â <h2>Heading 2</h2>Â Â </div>Â Â <div>Â Â Â Â <h1>Heading 3</h1>Â Â Â Â <h2>Heading 4</h2>Â Â </div></body>");Â
// Check if XML follows the relaxNG ruleif ($doc->relaxNGValidateSource($RNG)) {Â Â Â Â echo "This document is valid!\n";}?> |
Output:
This document is valid!
Program 2:Â
php
<?phpÂ
// Create a new DOMDocument$doc = new DOMDocument;Â
// RNG schema$RNG = "<element name=\"company\" Â Â Â Â xmlns=\"http://relaxng.org/ns/structure/1.0\"><zeroOrMore>Â Â <element name=\"employee\">Â Â Â Â <element name=\"name\">Â Â Â Â Â Â <text/>Â Â Â Â </element>Â Â Â Â <element name=\"salary\">Â Â Â Â Â Â <text/>Â Â Â Â </element>Â Â </element></zeroOrMore></element>";Â
// 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 violate rule -->Â Â Â Â <name>John Doe</name>Â Â </employee></company>");Â
// Check if XML doesn't follows the relaxNG ruleif (!$doc->relaxNGValidateSource($RNG)) {Â Â Â Â echo "This document is not valid!\n";}?> |
Output:
This document is not valid!
Reference: https://www.php.net/manual/en/domdocument.relaxngvalidatesource.php



