Search code examples
phpdomdocumentappendchildcreateelement

How to use DOMDocument insertBefore


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.


Solution

  • 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();