DOMDocument::schemaValidateSource()函數是PHP中的一個內置函數,用於基於給定字符串中定義的模式來驗證文檔。 schemaValidate()和schemaValidateSource()之間的區別在於,前者可以接受模式文件名,而後者可以接受模式作為字符串。
用法:
bool DOMDocument::schemaValidateSource( string $source, int $flags = 0 )
參數:該函數接受上述和以下所述的兩個參數:
- $source:它指定包含模式的字符串。
- $flags (Optional):它指定驗證標誌。
返回值:如果成功,則此函數返回TRUE;如果失敗,則返回FALSE。
下麵給出的程序說明了PHP中的DOMDocument::schemaValidateSource()函數:
程序1:
<?php 
  
// Create a new DOMDocument 
$doc = new DOMDocument; 
  
// XSD schema 
$XSD = "<?xml version=\"1.0\"?> 
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" 
elementFormDefault=\"qualified\"> 
    <xs:element name=\"body\"> 
        <xs:complexType> 
            <xs:sequence> 
                <xs:element name=\"h1\" type=\"xs:string\"/> 
                <xs:element name=\"strong\" type=\"xs:integer\"/> 
            </xs:sequence> 
        </xs:complexType> 
    </xs:element> 
</xs:schema>"; 
  
// Load the XML 
$doc->loadXML("<?xml version=\"1.0\"?> 
<body> 
    <h1> Hello </h1> 
    <strong> 22 </strong> 
</body>"); 
  
// Check if XML follows the schema rule 
if ($doc->schemaValidateSource($XSD)) { 
    echo "This document is valid!\n"; 
} 
?>輸出:
This document is valid!
程序2:
<?php 
  
// Create a new DOMDocument 
$doc = new DOMDocument; 
  
// RNG schema 
$XSD = "<?xml version=\"1.0\"?> 
<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\" 
elementFormDefault=\"qualified\"> 
    <xs:element name=\"student\"> 
        <xs:complexType> 
            <xs:sequence> 
                <xs:element name=\"name\" type=\"xs:string\"/> 
                <xs:element name=\"rollno\" type=\"xs:integer\"/> 
            </xs:sequence> 
        </xs:complexType> 
    </xs:element> 
</xs:schema>"; 
  
// Load the XML 
$doc->loadXML("<?xml version=\"1.0\"?> 
<student>  
    <!-- rollnow element is missing here --> 
    <name> XYZ </name> 
</student> 
"); 
  
// Check if XML follows the relaxNG rule 
if (!$doc->schemaValidateSource($XSD)) { 
    echo "This document is not valid!\n"; 
} 
?>輸出:
This document is not valid!
參考: https://www.php.net/manual/en/domdocument.schemavalidatesource.php
相關用法
- PHP DOMDocument load()用法及代碼示例
- PHP DOMDocument loadXML()用法及代碼示例
- PHP DOMDocument save()用法及代碼示例
- PHP DOMDocument getElementsByTagName()用法及代碼示例
- PHP DOMDocument loadHTML()用法及代碼示例
- PHP DOMDocument loadHTMLFile()用法及代碼示例
- PHP DOMDocument normalizeDocument()用法及代碼示例
- PHP DOMDocument schemaValidate()用法及代碼示例
- PHP DOMDocument saveHTML()用法及代碼示例
- PHP DOMDocument createProcessingInstruction()用法及代碼示例
- PHP DOMDocument relaxNGValidate()用法及代碼示例
- PHP DOMDocument relaxNGValidateSource()用法及代碼示例
- PHP DOMDocument createEntityReference()用法及代碼示例
- PHP DOMDocument saveHTMLFile()用法及代碼示例
- PHP DOMDocument importNode()用法及代碼示例
注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMDocument schemaValidateSource() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
