insertBefore()与PHP DOM无法正常工作

时间:2013-10-03 15:15:24

标签: php html dom

我有这个结构:

<p>Second paragraph</p>
<p>First paragraph</p>
<p>Third paragraph</p>

我想用PHP DOM重新排列元素,把它变成这样的东西:

<p>First paragraph</p>
<p>Second paragraph</p>
<p>Third paragraph</p>

我尝试使用以下代码执行此操作:

$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));

但是当我使用时:

echo $dom->getElementsByTagName('p')->item(0)->nodeValue;

我明白了:

First paragraphSecond paragraph

因此,我想我在这里做错了。

2 个答案:

答案 0 :(得分:2)

来自PHP Documentation

public DOMNode DOMNode::insertBefore ( DOMNode $newnode [, DOMNode $refnode ] )

refnode
    The reference node. If not supplied, newnode is appended to the children.

因此,由于您没有指定引用节点,因此它会将其附加到子节点。您的代码将生成此HTML:

<html>
<body>
    <p>First paragraph<p>Second paragraph</p></p>
    <p>Third paragraph</p>
</body>
</html>

您需要做的是执行insertBefore上的parentNode,参考第二段,如下所示:

$nodes = $dom->getElementsByTagName('p');
$nodes->item(0)->parentNode->insertBefore($nodes->item(1), $nodes->item(0));
echo $dom->saveHTML();

输出:

<html>
<body>
    <p>First paragraph</p>
    <p>Second paragraph</p>
    <p>Third paragraph</p>
</body>
</html>

答案 1 :(得分:1)

如果我回复所有文件:http://phpfiddle.org/main/code/kib-yn1