I've got this structure:
<p>Second paragraph</p>
<p>First paragraph</p>
<p>Third paragraph</p>
and I want to rearrange elements with PHP DOM to turn it into something like this:
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
I tried doing this with the following code:
$html = "<p>Second paragraph</p><p>First paragraph</p><p>Third paragraph</p>";
$dom = new domDocument;
$dom->loadHTML( $html );
$dom->getElementsByTagName('p')->item(1)->insertBefore($dom->getElementsByTagName('p')->item(0));
However when I use:
echo $dom->getElementsByTagName('p')->item(0)->nodeValue;
I get:
First paragraphSecond paragraph
as a result, so I guess I'm doing something wrong here.
From the PHP Documentation:
public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )
refnode
The reference node. If not supplied, newnode is appended to the children.
Therefore since you are not specifying the reference node it is appending it to the children. Your code will produce this HTML:
<html>
<body>
<p>First paragraph<p>Second paragraph</p></p>
<p>Third paragraph</p>
</body>
</html>
What you need to do is do the insertBefore
on the parentNode
, in reference to the Second Paragraph like so:
$nodes = $dom->getElementsByTagName('p');
$nodes->item(0)->parentNode->insertBefore($nodes->item(1), $nodes->item(0));
echo $dom->saveHTML();
Output:
<html>
<body>
<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>
</body>
</html>
If I echo all document it works: http://phpfiddle.org/main/code/kib-yn1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With