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