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


PHP DOMElement removeAttributeNode()用法及代码示例


DOMElement::removeAttributeNode()函数是PHP中的内置函数,用于从元素中删除属性。

用法:

bool DOMElement::removeAttributeNode( DOMAttr $oldnode )

参数:该函数接受单个参数$oldnode,该参数包含要删除的属性。



返回值:如果成功,则此函数返回TRUE;如果失败,则返回FALSE。

异常:如果节点是只读的,则此函数引发DOM_NO_MODIFICATION_ALLOWED_ERR;如果$oldnode不是element的属性,则此函数引发DOM_NOT_FOUND_ERROR。

下面给出的程序说明了PHP中的DOMElement::removeAttributeNode()函数:

程序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; 
  
// Get the attribute to remove 
$oldnode = $node->getAttributeNode('id'); 
  
// Remove the id attribute 
$node->removeAttributeNode($oldnode); 
  
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 string 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 to remove 
$oldnode = $node->getAttributeNode('id'); 
  
// Get the attribute count 
$attributeCount = $node->attributes->count(); 
echo 'No of attributes => ' . $attributeCount; 
  
// Remove the id attribute 
$node->removeAttributeNode($oldnode); 
  
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.removeattributenode.php




相关用法


注:本文由纯净天空筛选整理自gurrrung大神的英文原创作品 PHP | DOMElement removeAttributeNode() Function。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。