Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM php delete all tags by tag name

Tags:

html

dom

php

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

like image 867
Tadej Magajna Avatar asked May 08 '13 16:05

Tadej Magajna


1 Answers

Try this way:

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

while ($list->length > 0) {
    $p = $list->item(0);
    $p->parentNode->removeChild($p);
}
like image 193
Manuel Pedrera Avatar answered Oct 12 '22 16:10

Manuel Pedrera