A: 

Found a solution,

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

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

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

See my answer for explanation.
jmz
A: 

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);
karim79
Thanks a lot! You people made me see more clear where was the error.
+1  A: 

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);
}
jmz
Thanks a lot! You people made me see more clear where was the error.
If it's OK, accept one of the answers.
jmz