How to use DOMDocument insertBefore

◇◆丶佛笑我妖孽 提交于 2019-12-11 06:46:19

问题


I have a div and I'm trying to insert a couple elements (h3 and p) into the div ahead of the existing h3 and p elements already living inside the div. The PHP documentation for insertBefore (http://www.php.net/manual/en/domnode.insertbefore.php) says this is exactly what should happen, but instead of inserting ahead of the existing elements, its replacing all existing elements inside my 'content' div.

Here's my code:

$webpage = new DOMDocument();
$webpage->loadHTMLFile("news.html");

$headerelement = $webpage->createElement('h3', $posttitle);
$pelement = $webpage->createElement('p', $bodytext);

$webpage->formatOutput = true;
$webpage->getElementById('content')->insertBefore($headerelement);
$webpage->getElementById('content')->insertBefore($pelement);

$webpage->saveHTMLFile("newpost.html");

I'm sure I'm just not understanding something... any help would be appreciated, thanks.


回答1:


It's because you're not specifying a reference node that the inserted node should be inserted before. Think of it like this:

$whatTheElementIsInsertedInto->insertBefore($theElement, $whatItIsInsertedBefore)

Live demo (click).

$dom = new DOMDocument();

$dom->loadHtml('
  <html><head></head>
    <body>
      <div id="content">
        <h3>Original h3</h3>
      </div>
    </body>
  </html>
');

//find the "content" div
$content = $dom->getElementById('content');

//find the first h3 tag in "content"
$origH3 = $content->getElementsByTagName('h3')->item(0);

//create a new h3
$newH3 = $dom->createElement('h3', 'new h3!');

//insert the new h3 before the original h3 of "content"
$content->insertBefore($newH3, $origH3);

echo $dom->saveHTML();


来源:https://stackoverflow.com/questions/21416277/how-to-use-domdocument-insertbefore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!