2014-08-27 106 views
1

我試圖用給定的類刪除每個節點。PHP DOMDocument:按類刪除元素

要找到我使用的元素:

$xpath = new DOMXPath($dom); 
    foreach($xpath->query('//div[contains(attribute::class, "foo")]') as $e) { 
     // Delete this node 
    } 

但我怎麼能刪除此的foreach循環的元素呢?

編輯:順便說一句:如何檢查DOM中是否有類「foo」的元素(在啓動循環之前)?

更新:

這是我的HTML:

$xpath = new DOMXPath($dom); 
foreach($xpath->query('//div[contains(attribute::class, "delete_this")]') as $e) { 
    $e->parentNode->removeChild($e); 
} 

回答

7

您需要使用的的removeChild()方法:

<div class="main"> 
    <div class="delete_this" contenteditable="true">Target</div> 
    <div class="class1"></div> 
    <div class="content"><p>Anything</p></div> 
</div> 

這並不適用於上述的例子中工作父元素:

$xpath = new DOMXPath($dom); 
foreach($xpath->query('//div[contains(attribute::class, "foo")]') as $e) { 
    // Delete this node 
    $e->parentNode->removeChild($e); 
} 

順便說一句,關於你的第二個問題,如果沒有找到元素,循環將不會重複。


又來了一個工作示例:

$html = <<<EOF 
<div class="main"> 
    <div class="delete_this" contenteditable="true">Target</div> 
    <div class="class1"></div> 
    <div class="content"><p>Anything</p></div> 
</div> 
EOF; 

$doc = new DOMDocument(); 
$doc->loadHTML($html); 

$selector = new DOMXPath($doc); 
foreach($selector->query('//div[contains(attribute::class, "delete_this")]') as $e) { 
    $e->parentNode->removeChild($e); 
} 

echo $doc->saveHTML($doc->documentElement); 
+0

這對我不起作用。我已更新該帖子。 – user3142695 2014-08-27 17:30:00

+0

謝謝。我忘記了saveHTML :-( – user3142695 2014-08-27 18:06:38

+0

),不過,在這個例子中,你可以使用下面的查詢:'// div [@class =「delete_this」]' – hek2mgl 2014-08-27 18:12:09

1

對於問題的第二部分,查詢的結果具有length屬性,你可以用它來察看是否有匹配:

$xpath = new DOMXPath($doc); 
$nodes = $xpath->query('//div[contains(attribute::class, "foo")]'); 

printf('Removing %d nodes', $nodes->length);