2

我使用 DOMXPATH从标签中删除所有 内容,它工作正常,attributesp

// Loop all p.
foreach( $dom->getElementsByTagName( "p" ) as $p )
{
    // Loop all attributes in p.
    foreach( $p->attributes as $attrib )
    {
          // Remove all attribute   from p. 
          $p->removeAttributeNode( $attrib );
    }

}

现在我只想从 p 标签中删除样式。 attribute

// Loop all p.
foreach( $dom->getElementsByTagName( "p" ) as $p )
{
    // Loop all attributes in p.
    foreach( $p->attributes as $attrib )
    {
          // Remove only the style attribute
      $p->removeAttributeNode( $p->getAttributeNode( "style" ) );
    }

}

但我有这个错误作为回报,

可捕获的致命错误:传递给 DOMElement::removeAttributeNode() 的参数 1 必须是 DOMAttr 的实例,给定的布尔值..

如何仅删除样式 attribute

4

1 回答 1

3

替换这个

// Loop all attributes in p.
foreach( $p->attributes as $attrib )
{
      // Remove only the style attribute
  $p->removeAttributeNode( $p->getAttributeNode( "style" ) );
}

像这样:

// fetch style node
$sNode = $p->getAttributeNode( "style" )
// only procede, if $p actually has a style node
if ($sNode) {
  $p->removeAttributeNode( $sNode );
}

(未测试,抱歉,我这里没有安装服务器)

于 2012-03-27T15:28:21.023 回答