Im not really familiar with DOM.
Anyway what I am trying to do is add a new element before another element. Im using the insertBefore method which is suppose to when using two arguments add the element before the reference child.
<?php
/* quick warning this will only work in PHP 5 */
$dom = new domDocument();
$dom->load('example2.xml');
try
{
$dom->insertBefore($dom->createElement('name', 'My Name'), $dom->getElementsByTagName('body')->firstChild);
echo $dom->saveXML();
}
catch (DOMException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
This works all bar the insertBefore method tends to want to append the new name element at the end.
example2.xml
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<messages>
<body>Don't forget me this weekend!</body>
<body>Don't forget me this weekend2!</body>
</messages>
</note>
After using DOM
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<messages>
<body>Don't forget me this weekend!</body>
<body>Don't forget me this weekend2!</body>
</messages>
</note>
<name>My Name</name>
As you can see name is appended at the end of the file when it really should be put right before the first body child of messages.