XMLReader::setRelaxNGSchema()函數是PHP中的內置函數,用於為RelaxNG Schema設置文件名或URI以用於驗證。
用法:
bool XMLReader::setRelaxNGSchema( string $filename )
參數:該函數接受單個參數$filename,該參數包含指向RelaxNG Schema的文件名或URI。
返回值:如果成功,此函數將返回TRUE,否則將返回FALSE。
以下示例說明了PHP中的XMLReader::setRelaxNGSchema()函數:
-
範例1:
- data.xml(要驗證的XML文件)
<?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>
- 規則(XML文件要遵循的規則)
<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>
- index.php(PHP腳本運行驗證器)
<?php // Create a new XMLReader instance $XMLReader = new XMLReader(); // Open the XML file $XMLReader->open('data.xml'); // Load the rule file $XMLReader->setRelaxNGSchema('rule.rng'); // Iterate through the XML nodes // and validate each node while ($XMLReader->read()) { if ($XMLReader->nodeType == XMLREADER::ELEMENT) { // Check if XML follows the relaxNG rule if ($XMLReader->isValid()) { echo "This document is valid!<br>"; } } } ?>
- 輸出:
This document is valid! This document is valid! This document is valid! This document is valid! This document is valid! This document is valid! This document is valid!
程序2:
- data.xml
<?xml version="1.0"?> <body> <div> <!--Remove Heading 1 to violate rule--> <h2>Heading 2</h2> </div> <div> <h1>Heading 3</h1> <h2>Heading 4</h2> </div> </body>
- 規則
<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>
- index.php
<?php // Create a new XMLReader instance $XMLReader = new XMLReader(); // Open the XML file $XMLReader->open('data.xml'); // Load the rule file $XMLReader->setRelaxNGSchema('rule.rng'); // Iterate through the XML nodes while ($XMLReader->read()) { if ($XMLReader->nodeType == XMLREADER::ELEMENT) { // Check if XML follows the relaxNG rule if (!$XMLReader->isValid()) { echo "This document is not valid!<br>"; } } } ?>
- 輸出:
This document is not valid! This document is not valid! This document is not valid! This document is not valid!
參考: https://www.php.net/manual/en/xmlreader.setrelaxngschema.php
相關用法
- PHP XMLReader XML()用法及代碼示例
- PHP XMLReader close()用法及代碼示例
- PHP XMLReader getAttributeNs()用法及代碼示例
- PHP XMLReader open()用法及代碼示例
- PHP XMLReader getParserProperty()用法及代碼示例
- PHP XMLReader moveToFirstAttribute()用法及代碼示例
- PHP XMLReader moveToNextAttribute()用法及代碼示例
- PHP XMLReader readInnerXml()用法及代碼示例
- PHP XMLReader readOuterXml()用法及代碼示例
- PHP XMLReader readString()用法及代碼示例
- PHP XMLReader setParserProperty()用法及代碼示例
- PHP XMLReader setRelaxNGSchemaSource()用法及代碼示例
- PHP XMLReader setSchema()用法及代碼示例
注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | XMLReader setRelaxNGSchema() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。