DOMDocument::validate()函數是PHP中的一個內置函數,用於根據其DTD(文檔類型定義)來驗證文檔。 DTD定義XML文件要遵循的規則或結構,如果XML文檔未遵循此格式,則此函數將返回false。
用法:
bool DOMDocument::validate( void )
參數:此函數不接受任何參數。
返回值:如果文檔遵循DTD或FALSE,則此函數返回TRUE。
以下示例說明了PHP中的DOMDocument::validate()函數:
範例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"; 
} 
?>輸出:
This document is valid!
範例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!"; 
} 
?>輸出:
This document is not valid!
參考: https://www.php.net/manual/en/domdocument.validate.php
相關用法
- PHP DOMDocument createDocumentFragment()用法及代碼示例
- PHP DOMDocument importNode()用法及代碼示例
- PHP DOMDocument getElementsByTagName()用法及代碼示例
- PHP DOMDocument createAttribute()用法及代碼示例
- PHP DOMDocument __construct()用法及代碼示例
- PHP DOMDocument createEntityReference()用法及代碼示例
- PHP DOMDocument createProcessingInstruction()用法及代碼示例
- PHP DOMDocument createTextNode()用法及代碼示例
- PHP DOMDocument saveXML()用法及代碼示例
- PHP DOMDocument getElementById()用法及代碼示例
- PHP DOMDocument registerNodeClass()用法及代碼示例
- PHP DOMDocument xinclude()用法及代碼示例
- PHP DOMDocument createCDATASection()用法及代碼示例
- PHP DOMDocument schemaValidateSource()用法及代碼示例
- PHP DOMDocument schemaValidate()用法及代碼示例
注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMDocument validate() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
