略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: DOMElement::removeAttributeNode

2024-12-21

DOMElement::removeAttributeNode

(PHP 5, PHP 7, PHP 8)

DOMElement::removeAttributeNodeRemoves attribute

说明

public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false

Removes attribute attr from the element.

参数

attr

The attribute node.

返回值

成功时返回 true, 或者在失败时返回 false

错误/异常

DOM_NO_MODIFICATION_ALLOWED_ERR

Raised if the node is readonly.

DOM_NOT_FOUND_ERROR

Raised if attr is not an attribute of the element.

参见

add a noteadd a note

User Contributed Notes 1 note

up
2
xr07354 at gmx dot de
9 years ago
Basic: I use PHP5.4.9 from Ubuntu 13.04 repository. The aim of my code is to iterate HTML source (as a DomDocument) recursively and cleanup everything that is not valid to be used inside Epub files (i.e. and attribute align is not valid for paragraphs in Epubs).

FIRST: Today I tried removing attributes from a DOMElement using this simple code:
<?php
for ( $k=0; $k < $element->attributes->length; $k++) {
    if(
/* some rule */ ){
       
var_dump( $element->attributes->item($k)->nodeName);
       
$element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
Unfortunately all attributes still existed when this loop was finished, even if these var_dumps told me that deleting them was tried.

I solved this problem iterating the attributes list backward:
<?php
for ( $k = $element->attributes->length - 1; $k >= 0; --$k) {
    if(
/* same rule */ ){
       
var_dump( $element->attributes->item($k)->nodeName);
       
$element->removeAttributeNode( $element->attributes->item($k));
    }
}
?>
SECOND: DOMElement::removeAttributeNode does NOT return a bool but a DOMAttr object.

官方地址:https://www.php.net/manual/en/domelement.removeattributenode.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3