Tuesday, November 19, 2024
Google search engine
HomeLanguagesPHP | DOMDocument relaxNGValidateSource() Function

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 rule
if ($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 rule
if (!$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

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments