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


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。