6
votes

I'm having a problem with a script I've been using for some time and it worked for me until I hit this problem.

I have a script with which I'd like to delete all p html tags from a html source code. The script does work partly because it only removes some of the p tags, but leaves some out.

I don't understand why it does that.

$doc = new DOMDocument();

$a = <<<FAIL
<html><body>
<div style="clear:both"></div>
<p class="articletitle">hoo</p>
<p class="articletext">hmmm</p>
<p class="articletext">hmmmm</p>
<p align="center"></p>
</body></html>
FAIL;

$doc->loadHTML($a);
$list = $doc->getElementsByTagName("p");

foreach ($list as $l) {
$l->parentNode->removeChild($l);
$c++;
}
echo $doc->saveHTML() . $c;

the script returns

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html><body>
<div style="clear:both"></div>

<p class="articletext">hmmm</p>

<p align="center"></p>

leaving out two p tags...

Can you please help me to find out why it's skipping some tags

1
Someone using HEREDOC, what a miracle.Wesley Schleumer de Góes
generally speaking, you should delete nodes from the bottom of the tree upwards, instead of top->down as you are. The results of DOM search operations become undefined if you modify the tree after the search completes.Marc B

1 Answers

12
votes

Try this way:

$doc->loadHTML($a);
$list = $doc->getElementsByTagName("p");

while ($list->length > 0) {
    $p = $list->item(0);
    $p->parentNode->removeChild($p);
}