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


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


DOMElement::removeAttribute()函數是PHP中的內置函數,用於從元素中刪除具有特定名稱的屬性。

用法:

bool DOMElement::removeAttribute( string $name )

參數:該函數接受單個參數$name,該參數保存屬性的名稱。


返回值:如果成功,則此函數返回TRUE;如果失敗,則返回FALSE。

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

以下示例說明了PHP中的DOMElement::removeAttribute()函數:

範例1:

<?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 removal of attributes:<br>"; 
  
// Get the attribute name and value 
$attribute = $node->attributes->item(0); 
$attribute_name = $attribute->name; 
$attribute_value = $attribute->value; 
  
echo $attribute_name . ' => '; 
echo $attribute_value; 
  
// Remove the id attribute 
$node->removeAttribute('id'); 
  
echo "<br>After the removal of attributes:<br>"; 
  
// Get the attribute name and value 
$attribute = $node->attributes->item(0); 
$attribute_name = $attribute->name . ' => '; 
$attribute_value = $attribute->value; 
echo $attribute_name; 
echo $attribute_value; 
?>

輸出:

Before the removal of attributes:
id => my_id
After the removal of attributes:
=> // Empty value means attribute is removed

範例2:

<?php 
   
// Create a new DOMDocument 
$dom = new DOMDocument(); 
   
// Load the XML 
$dom->loadXML("<?xml version=\"1.0\"?> 
<root> 
    <html> 
        <h1 id=\"my_id\"  
            style=\"color:green;\"  
            class=\"my_class\">  
            Geeksforgeeks  
        </h1> 
        <h2> Second heading </h2> 
    </html> 
</root>"); 
   
// Get the elements 
$node = $dom->getElementsByTagName('h1')[0]; 
   
echo "Before the removal of attributes:<br>"; 
   
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
   
// Remove the id attribute 
$node->removeAttribute('id'); 
   
echo "<br>After the removal of attributes:<br>"; 
   
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
?>

輸出:

Before the removal of attributes:
No of attributes => 3
After the removal of attributes:
No of attributes => 2

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



相關用法


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