當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP XMLReader isValid()用法及代碼示例

XMLReader::isValid()函數是PHP中的一個內置函數,用於檢查所解析的文檔是否有效。如果遵循定義所有允許的元素和元素結構的DTD(文檔類型定義)來編寫XML,則該XML是有效的。

用法:

bool XMLReader::isValid( void )

參數:此函數不接受任何參數。



返回值:如果成功,則此函數返回TRUE;如果失敗,則返回FALSE。

下麵給出的程序說明了PHP中的XMLReader::isValid()函數:

程序1:
文檔名稱: data.xml

<?xml version="1.0"?> 
<!-- DTD rules to be followed by XML-->
<!DOCTYPE html [ 
<!ELEMENT html (h1, p, heading, body)> 
<!ELEMENT h1 (#PCDATA)> 
<!ELEMENT p (#PCDATA)> 
<!ELEMENT heading (#PCDATA)> 
<!ELEMENT body (#PCDATA)> 
]> 
  
<!-- XML starts from here -->
<html> 
<h1>Hi</h1> 
<p>World</p> 
<heading>GeeksforGeeks</heading> 
<body>Web Portal for Geeks</body> 
</html>

文檔名稱: index.php

<?php 
  
// Create a new XMLReader instance 
$XMLReader = new XMLReader(); 
  
// Open the XML file 
$XMLReader->open('data.xml'); 
  
// Enable the Parser Property 
$XMLReader->setParserProperty( 
       XMLReader::VALIDATE, true); 
  
// Iterate through the XML nodes 
while ($XMLReader->read()) { 
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) { 
  
        // Check if XML is valid or not 
        $isValid = $XMLReader->isValid(); 
        if ($isValid) { 
            echo "YES ! this node is validated<br>"; 
        } 
    } 
} 
?>

輸出:

YES ! this node is validated
YES ! this node is validated
YES ! this node is validated
YES ! this node is validated
YES ! this node is validated

程序2:
文檔名稱: data.xml

<?xml version="1.0"?> 
<!-- DTD rules to be followed by XML--> 
<!DOCTYPE html [ 
<!ELEMENT html (heading, body)> 
<!ELEMENT heading (#PCDATA)> 
<!ELEMENT body (#PCDATA)> 
]> 
<!-- XML starts from here --> 
<html> 
<body>Web Portal for Geeks</body> 
</html>

文檔名稱: index.php

<?php 
  
// Create a new XMLReader instance 
$XMLReader = new XMLReader(); 
  
// Open the XML file 
$XMLReader->open('data.xml'); 
  
// Enable the Parser Property 
$XMLReader->setParserProperty( 
         XMLReader::VALIDATE, true); 
  
// Iterate through the XML nodes 
while ($XMLReader->read()) { 
    if ($XMLReader->nodeType == XMLREADER::ELEMENT) { 
  
        // Check if XML is valid or not 
        $isValid = $XMLReader->isValid(); 
        if (!$isValid) { 
            echo "No ! this node is not validated<br>"; 
        } 
    } 
} 
?>

輸出:

No ! this node is not validated
No ! this node is not validated

參考: https://www.php.net/manual/en/xmlreader.isvalid.php




相關用法


注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | XMLReader isValid() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。