Tutorial :PHP DOMDocument: insertBefore, how to make it work?


I would like to place a new node element, before a given element. I'm using insertBefore for that, without success!

Here's 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>  


Any kind of help is appreciated, thanks!


If maindiv is from getElementsByTagName(), then $maindiv->item(0) is the div with id=maindiv. So your code is working correctly because you're asking it to place the new div before maindiv.

To make it work like you want, you need to get the children of maindiv:

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

Note that if you don't have a DTD, PHP doesn't return anything with getElementsById. For getElementsById to work, you need to have a DTD or specify which attributes are IDs:

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


Found a solution,

            $child = $maindiv->item(0);                $child->insertBefore( $div, $child->firstChild );   

I dont know how much sense this makes, but well, worked.


From scratch, this seems to work too:

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »