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


PHP DOMElement setAttributeNode()用法及代碼示例

DOMElement::setAttributeNode()函數是PHP中的內置函數,用於向元素添加新的屬性節點。

用法:

DOMAttr DOMElement::setAttributeNode( DOMAttr $attr )

參數:該函數接受單個參數$attr,該參數保存要添加的屬性節點。



返回值:如果該值已被替換或為NULL,則此函數返回包含舊節點的DOMAttr值。

異常:如果節點是隻讀的,則此函數將拋出DOM_NO_MODIFICATION_ALLOWED_ERR。

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

程序1:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
   
// Create an element 
$node = $dom->createElement("p", 'GeeksforGeeks'); 
   
// Add the node to the dom 
$newnode = $dom->appendChild($node); 
   
// Create a DOMAttr instance which 
// increase the font-size 
$attr = new DOMAttr('style', 'font-size:80px;'); 
  
// Set the attribute 
$newnode->setAttributeNode($attr); 
   
// View the XML 
echo $dom->saveXML(); 
?>

輸出:

<?xml version="1.0"?>
<p style="font-size:80px;">GeeksforGeeks</p>

程序2:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Load the XML 
$dom->loadXML("<?xml version=\"1.0\"?> 
<root> 
    <html> 
        <h1 id=\"my_id\"> Geeksforgeeks </h1> 
        <h2> Second heading </h2> 
    </html> 
</root>"); 
  
// Get the elements 
$node = $dom->getElementsByTagName('h1')[0]; 
   
echo "Before the addition of attributes:<br>"; 
  
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
   
// Create a DOMAttr instance 
$attr = new DOMAttr('class', 'value'); 
  
// Add the new attribute 
$node->setAttributeNode($attr); 
   
echo "<br>After the addition of attributes:<br>"; 
   
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
?>

輸出:

Before the addition of attributes:
No of attributes => 1
After the addition of attributes:
No of attributes => 2

參考: https://www.php.net/manual/en/domelement.setattributenode.php




相關用法


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