如何仅使用DOMXPATH删除样式属性


How to remove style attribute only with DOMXPATH?

我使用DOMXPATH从p标签中删除所有attributes,它运行良好,

// 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" ) );
    }
}

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

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

如何仅删除样式attribute

替换此

// 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 );
}

(没有测试,对不起,我这里没有安装服务器)