PHP DOMDocument: insertBefore, how to make it work?

I want to add a new node element before this element. I use insertBefore for this, without success!

Here is the code

<DIV id="maindiv">

<!-- I would like to place the new element here -->

<DIV id="child1">

    <IMG />

    <SPAN />

</DIV>

<DIV id="child2">

    <IMG />

    <SPAN />

</DIV>

//$div is a new div node element,
//The code I'm trying, is the following:

$maindiv->item(0)->parentNode->insertBefore( $div, $maindiv->item(0) ); 

//Obs: This code asctually places the new node, before maindiv
//$maindiv object(DOMNodeList)[5], from getElementsByTagName( 'div' )
//echo $maindiv->item(0)->nodeName gives 'div'
//echo $maindiv->item(0)->nodeValue gives the correct data on that div 'some random text'
//this code actuall places the new $div element, before <DIV id="maindiv>

http://pastie.org/1070788

Any help is appreciated, thanks!

+5
source share
3 answers

If maindiv is from getElementsByTagName(), then $maindiv->item(0)this is a div with id = maindiv. This way your code works correctly because you are asking it to place a new div in front of the maindiv.

To make it work the way you want, you need to get the children from maindiv:

$dom = new DOMDocument();
$dom->load($yoursrc);
$maindiv = $dom->getElementById('maindiv');
$items = $maindiv->getElementsByTagName('DIV');
$items->item(0)->parentNode->insertBefore($div, $items->item(0));

, DTD, PHP getElementsById. getElementsById DTD , :

foreach ($dom->getElementsByTagName('DIV') as $node) {
    $node->setIdAttribute('id', true);
}
+5

,

            $child = $maindiv->item(0);

            $child->insertBefore( $div, $child->firstChild ); 

, , , .

0

From scratch, this also works:

$str = '<DIV id="maindiv">Here is text<DIV id="child1"><IMG /><SPAN /></DIV><DIV id="child2"><IMG /><SPAN /></DIV></DIV>';
$doc = new DOMDocument();
$doc->loadHTML($str);
$divs = $doc->getElementsByTagName("div");
$divs->item(0)->appendChild($doc->createElement("div", "here is some content"));
print_r($divs->item(0)->nodeValue);
0
source

All Articles