当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。