Search code examples
phpxpathphp-5.3domxpath

How to remove style attribute only with DOMXPATH?


I use DOMXPATH to remove all attributes from the p tag and it works fine,

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

}

And now I want to remove style attribute only from the p tag.

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

}

But I have this error in return,

Catchable fatal error: Argument 1 passed to DOMElement::removeAttributeNode() must be an instance of DOMAttr, boolean given..

How can I remove style attribute only?


Solution

  • replace this

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

    with something like this:

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

    (not tested, sorry, i don't have a server installed here)