6

我有这个结构:

<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

结果,所以我想我在这里做错了。

4

2 回答 2

3

来自PHP 文档

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>
于 2013-10-03T15:59:45.807 回答
1

如果我回显所有文档,它可以工作: http: //phpfiddle.org/main/code/kib-yn1

于 2013-10-03T15:27:06.913 回答