Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insertBefore() not working properly with PHP DOM

Tags:

html

dom

php

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.

like image 440
Mentalhead Avatar asked Oct 03 '13 15:10

Mentalhead


2 Answers

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>
like image 181
immulatin Avatar answered Nov 03 '22 00:11

immulatin


If I echo all document it works: http://phpfiddle.org/main/code/kib-yn1

like image 41
M. Foti Avatar answered Nov 02 '22 23:11

M. Foti