2 years ago

#69227

test-img

Álvaro Franz

PHP DOMDocument move a node to the top of a document

I want to reorganize scripts and styles in a piece of HTML that looks like:

<script ...></script>
<style ... >
<script ...></script>
<script ...></script>
<style ... >
<script ...></script>

So what I want to do is iterate over all style elements and move them to the top of the document. So that the end result looks like:

<style ... >
<style ... >
<script ...></script>
<script ...></script>
<script ...></script>
<script ...></script>

I managed to iterate over the DOM Document and remove the matched nodes, but I don't know how to add them again to the top of the document.

foreach(iterator_to_array($dom->getElementsByTagName('style')) as $node) {
  $node->parentNode->removeChild($node);
};

How can I achieve this?

php

domdocument

0 Answers

Your Answer

Accepted video resources