I have the following HTML.
<div id="container">
<div id="current">Current Div</div>
</div>
Using DomDocument in PHP, I am trying to add an extra div to the HTML before the div with the id of "current".
<div id="container">
<div id="new">New Div</div>
<div id="current">Current Div</div>
</div>
When I use the following code, it appears to add the div inside the div with the id of "current", but before the content of this div.Can anyone tell me why this is and how I can get the results like the HTML above? (See HTML Issue Below)
Current PHP
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->loadHTMLFile('index.html');
$head = $doc->getElementById('current');
$base = $doc->createElement('div', 'New Div');
$base->setAttribute('id', 'new');
echo $doc->saveHTML();
HTML Issue
<div id="container">
<div id="current">
<div id="new">New Div</div>
Current Div
</div>
</div>
EDIT:
PHP
$doc = new DOMDocument();
$doc->formatOutput = true;
$doc->loadHTMLFile('index.html');
$container = $doc->getElementById('container');
$current = $doc->getElementById('username');
$new = $doc->createElement('div', 'New Div');
$new->setAttribute('id', 'new');
$container->insertBefore($new, $current);
echo $doc->saveHTML();
HTML
<div id="container">
<form method="post" action="">
<input type="text" name="username" id="username" />
</form>
</div>
Error:
Fatal error: Uncaught exception 'DOMException' with message 'Not Found Error'
in index.php:55 Stack trace: #0 index.php(55):
DOMNode->insertBefore(Object(DOMElement), Object(DOMElement))