PHP | DOMElement removeAttributeNode()函数
DOMElement::removeAttributeNode()函数是PHP中的一个内置函数,用于从元素中删除属性。
句法:
bool DOMElement::removeAttributeNode( DOMAttr $oldnode )
参数:此函数接受单个参数$oldnode ,其中包含要删除的属性。
返回值:此函数在成功时返回 TRUE,在失败时返回 FALSE。
例外:如果节点是只读的,则此函数抛出 DOM_NO_MODIFICATION_ALLOWED_ERR,如果$oldnode不是元素的属性,则抛出 DOM_NOT_FOUND_ERROR。
下面给出的程序说明了PHP中的DOMElement::removeAttributeNode()函数:
方案一:
loadXML("
Geeksforgeeks
Second heading
");
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
echo "Before the removal of attributes:
";
// 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 "
After the removal of attributes:
";
// 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
方案二:
loadXML("
Geeksforgeeks
Second heading
");
// Get the elements
$node = $dom->getElementsByTagName('h1')[0];
echo "Before the removal of attributes:
";
// 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 "
After the removal of attributes:
";
// 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