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


PHP DOMNode normalize()用法及代碼示例

DOMNode::normalize()函數是PHP中的內置函數,用於刪除空文本節點並合並該節點及其所有子節點中的相鄰文本節點。

用法:

void DOMNode::normalize( void )

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


返回值:該函數不返回任何值。

以下示例說明了PHP中的DOMNode::normalize()函數:

範例1:在此程序中,我們將顯示normalize如何刪除空文本節點。

<?php 
   
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
   
// Create a div element 
$element = $document-> 
    appendChild(new DOMElement('div')); 
   
// Create a text Node 
$text1 = $document-> 
    createTextNode('GeeksforGeeks'); 
   
// Create a empty text Node 
$text2 = $document->createTextNode(''); 
   
// Create another empty text Node 
$text3 = $document->createTextNode(''); 
   
// Append the nodes 
$element->appendChild($text1); 
$element->appendChild($text2); 
$element->appendChild($text3); 
   
echo "Number of text nodes before normalization:"; 
echo count($element->childNodes) . "<br>"; 
   
// Normalize the document 
$document->normalize(); 
   
echo "Number of text nodes after normalization:"; 
echo count($element->childNodes); 
?>

輸出:

Number of text nodes before normalization:3
Number of text nodes after normalization:1

範例2:在此程序中,我們將顯示標準化如何合並所有鄰居文本節點。

<?php 
  
// Create a new DOMDocument instance 
$document = new DOMDocument(); 
  
// Create a div element 
$element = $document-> 
    appendChild(new DOMElement('div')); 
  
// Create a text Node 
$text1 = $document-> 
               createTextNode('Hello'); 
  
// Create another text Node 
$text2 = $document-> 
               createTextNode('World'); 
  
// Append the nodes 
$element->appendChild($text1); 
$element->appendChild($text2); 
  
echo "Number of text nodes "
                . "before normalization:"; 
echo count($element->childNodes) . "<br>"; 
  
// Normalize the document 
$document->normalize(); 
  
echo "Number of text nodes after "
                         . "normalization:"; 
echo count($element->childNodes); 
?>

輸出:

Number of text nodes before normalization:2
Number of text nodes after normalization:1

參考: https://www.php.net/manual/en/domnode.normalize.php



相關用法


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