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


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

DOMNode::insertBefore()函數是PHP中的內置函數,用於在某個特定節點之前插入新節點。

用法:

DOMNode DOMNode::insertBefore( DOMNode $newNode, DOMNode $refNode )

參數:該函數接受上述和以下描述的兩個參數:



  • $newNode:它指定新節點。
  • $refNode(可選):它指定參考節點。如果未提供,則將newnode附加到子項。

返回值:該函數返回插入的節點。

異常:如果此節點是隻讀的,或者要插入的節點的上一個父節點是隻讀的,則此函數將拋出DOM_NO_MODIFICATION_ALLOWED_ERR。 DOM_HIERARCHY_REQUEST_ERR,如果此節點的類型不允許$newNode節點類型的子級,或者要附加的節點是該節點的祖先之一或該節點本身,則DOM_WRONG_DOCUMENT_ERR,如果$newNode是從其他節點創建的如果$refNode不是該節點的子節點,則該文檔要比創建該節點的節點DOM_NOT_FOUND的文檔大。

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

程序1:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Create a paragraph element 
$p_element = $dom->createElement('p',  
      'This is the paragraph element!'); 
  
// Append the child 
$dom->appendChild($p_element); 
  
// Create a paragraph element 
$h_element = $dom->createElement('h1',  
      'This is the heading element!'); 
  
// Insert heading before HTML 
$dom->insertBefore($h_element, $p_element); 
  
// Render the output 
echo $dom->saveXML(); 
?>

輸出:

<?xml version="1.0"?>
<h1>This is the heading element!</h1>
<p>This is the paragraph element!</p>

程序2:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Create a paragraph element 
$p_element = $dom->createElement('p',  
      'GeeksforGeeks, paragraph'); 
  
// Append the child 
$dom->appendChild($p_element); 
  
// Create a paragraph element 
$h_element = $dom->createElement('h1', 
      'GeeksforGeeks, heading'); 
  
// When second argument is not provided 
// It will appended to the child 
$dom->insertBefore($h_element); 
  
// Render the output 
echo $dom->saveXML(); 
?>

輸出:

<?xml version="1.0"?>
<p>GeeksforGeeks, paragraph</p>
<h1>GeeksforGeeks, heading</h1>

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




相關用法


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