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