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

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 = new DOMDocument;
      
    // 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 rule
    if ($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 = new DOMDocument;
      
    // 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 rule
    if (!$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

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments