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


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

DOMElement::setAttribute()函數是PHP中的內置函數,用於將具有給定名稱的屬性設置為給定值。如果該屬性不存在,則將創建它。

用法:

DOMAttr DOMElement::setAttribute( string $name, string $value )

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



  • $name:它指定屬性的名稱。
  • $value:它指定屬性的值。

返回值:如果成功,此函數返回DOMAttr,如果錯誤則返回FALSE。

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

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

程序1:

<?php 
  
// Create a new DOMDocument 
$dom = new DOMDocument(); 
  
// Create an element 
$node = $dom->createElement("p", 
     'Hello, this is my paragraph.'); 
  
// Add the node to the dom 
$newnode = $dom->appendChild($node); 
  
// Set the attribute 
$newnode->setAttribute("style", "color:red"); 
  
echo $dom->saveXML(); 
?>

輸出:

<?xml version="1.0"?>
<p style="color:red">Hello, this is my paragraph.</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; 
   
// Set the id attribute 
$node->setAttribute('new', 'value'); 
   
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.setattribute.php




相關用法


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