2012-03-27 83 views
2

我用DOMXPATH從p標籤去除所有attributes,它工作正常,如何僅使用DOMXPATH刪除樣式屬性?

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

} 

但我有回報這個錯誤,

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

我怎樣才能刪除風格attribute只?

回答

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

(未測試,對不起,我沒有在這裏安裝了服務器)

+0

非常感謝你。有用! :-) – laukok 2012-03-27 15:33:19