DOMElement::setAttributeNodeNS()函數是PHP中的內置函數,用於向元素添加新的屬性節點。這隻是setAttributeNode()函數的替代方法。
用法:
DOMAttr DOMElement::setAttributeNodeNS( DOMAttr $attr )
參數:該函數接受單個參數$attr,該參數保存要添加的屬性。
返回值:如果屬性已被替換,則此函數返回舊節點。
異常:如果節點是隻讀的,則此函數將拋出DOM_NO_MODIFICATION_ALLOWED_ERR。
以下示例說明了PHP中的DOMElement::setAttributeNodeNS()函數:
範例1:
<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Create a element with a namespace 
$root = $dom->createElementNS("my_namepsace", "root"); 
   
// Create an element 
$node = $dom->createElement("div", "GeeksforGeeks"); 
   
// Append the child 
$dom->appendChild($root); 
  
// Add the node to the dom 
$newnode = $dom->appendChild($node); 
  
// Create a DOMAttr instance 
$attr = new DOMAttr('style', 'color:green; font-size:100px;'); 
  
// Set the attribute 
$newnode->setAttributeNodeNS($attr); 
   
echo $dom->saveXML(); 
?>輸出:

範例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->setAttributeNodeNS($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.setattributenodens.php
相關用法
- PHP DOMElement hasAttributeNS()用法及代碼示例
 - PHP DOMElement setAttributeNS()用法及代碼示例
 - PHP DOMElement setIdAttributeNode()用法及代碼示例
 - PHP DOMElement setIdAttributeNS()用法及代碼示例
 - PHP DOMElement setIdAttribute()用法及代碼示例
 - PHP DOMElement getElementsByTagName()用法及代碼示例
 - PHP DOMElement getAttributeNodeNS()用法及代碼示例
 - PHP DOMElement getAttribute()用法及代碼示例
 - PHP DOMElement __construct()用法及代碼示例
 - PHP DOMElement getAttributeNS()用法及代碼示例
 - PHP DOMElement getAttributeNode()用法及代碼示例
 - PHP DOMElement removeAttributeNS()用法及代碼示例
 - PHP DOMElement removeAttribute()用法及代碼示例
 
注:本文由純淨天空篩選整理自gurrrung大神的英文原創作品 PHP | DOMElement setAttributeNodeNS() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
