2

I want to remove all script element and here the code

<?php
$pageFile = <<<EOF
<!DOCTYPE html><html><body>
<script src="aa"></script>
<script src="bb"></script>
<script src="cc"></script>
<div>aaa</div>
</body></html>
EOF;

$dom = new DOMDocument();
$dom->loadHTML($pageFile);

foreach ($dom->getElementsByTagName('script') as $item) {
  $item->parentNode->removeChild($item);
}
$pageFile = $dom->saveHTML();
echo $pageFile;

but there still 1 script element exist. You can try it online here

Result:

<!DOCTYPE html>
<html><body>
<script src="bb"></script><div>aaa</div>
</body></html>

2 Answers 2

4

The DOMNodeList returned by $dom->getElementsByTagName is "live". So when you remove a script, it's removed from the node list, and all the elements of the list shift their indexes down. Then the for loop goes to the next index, and it ends up skipping every other element.

Convert the node list to an array first.

foreach (iterator_to_array($dom->getElementsByTagName('script')) as $item) {
  $item->parentNode->removeChild($item);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can modify, and even delete, nodes from a DOMNodeList if you iterate backwards: http://php.net/manual/en/class.domnodelist.php#83390 use:

<?php
$pageFile = <<<EOF
<!DOCTYPE html><html><body>
<script src="aa"></script>
<script src="bb"></script>
<script src="cc"></script>
<div>aaa</div>
</body></html>
EOF;

$dom = new DOMDocument();
$dom->loadHTML($pageFile);
$elements = $dom->getElementsByTagName('script');
for ($i = $elements->length; --$i >= 0; ) {
  $elem = $elements->item($i);
  $elem->parentNode->removeChild($elem);
}
$pageFile = $dom->saveHTML();
echo $pageFile;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.