The DOMDocument::validate() function is an inbuilt function in PHP which is used to validate the document based on its DTD (Document Type Definition). DTD defines the rules or structure to be followed by the XML file and if a XML document doesn’t follows this format then this function will return false.
Syntax:
bool DOMDocument::validate( void )
Parameters: This function doesn’t accept any parameters.
Return Value: This function returns TRUE if document follows the DTD or FALSE.
Below examples illustrate the DOMDocument::validate() function in PHP:
Example 1:
<?php // Create a new DOMDocument $doc = new DOMDocument; // Load the XML with DTD rule to have // a root element with first, second, // and third as its three children $doc->loadXML("<?xml version=\"1.0\"?> <!DOCTYPE root [ <!ELEMENT root (first, second, third)> <!ELEMENT first (#PCDATA)> <!ELEMENT second (#PCDATA)> <!ELEMENT third (#PCDATA)> ]> <!-- Create a XML following the DTD --> <root> <first>Hello</first> <second>There</second> <third>World</third> </root>"); // Check if XML follows the DTD rule if ($doc->validate()) { echo "This document is valid!\n"; } ?> |
Output:
This document is valid!
Example 2:
<?php // Create a new DOMDocument $doc = new DOMDocument; // Load the XML $doc->loadXML("<?xml version=\"1.0\"?> <!DOCTYPE root [ <!ELEMENT root (one, two, three)> <!ELEMENT one (#PCDATA)> <!ELEMENT two (#PCDATA)> <!ELEMENT three (#PCDATA)> ]> <!-- Create a XML voilating the DTD --> <root> <one>Hello</one> <two>World</two> </root>"); if (!$doc->validate()) { echo "This document is not valid!"; } ?> |
Output:
This document is not valid!
Reference: https://www.php.net/manual/en/domdocument.validate.php
Recommended Posts:
- PHP | DOMDocument xinclude() Function
- PHP | DOMDocument createCDATASection() Function
- PHP | DOMDocument createComment() Function
- PHP | DOMDocument createElement() Function
- PHP | DOMDocument createAttribute() Function
- PHP | DOMDocument __construct() Function
- PHP | DOMDocument getElementsByTagName() Function
- PHP | DOMDocument importNode() Function
- PHP | DOMDocument saveXML() Function
- PHP | DOMDocument createTextNode() Function
- PHP | DOMDocument createProcessingInstruction() Function
- PHP | DOMDocument createEntityReference() Function
- PHP | DOMDocument saveHTMLFile() Function
- PHP | DOMDocument saveHTML() Function
- PHP | DOMDocument save() Function
- PHP | DOMDocument loadXML() Function
- PHP | DOMDocument normalizeDocument() Function
- PHP | DOMDocument loadHTMLFile() Function
- PHP | DOMDocument loadHTML() Function
- PHP | DOMDocument load() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

