This will work. Let me know if you need explanation :)
<?php
ini_set( 'display_errors', 1 );
ini_set( 'error_reporting', E_ALL );
$dom = new DOMDocument( '1.0' );
$dom->formatOutput = true;
$dom->preserveWhiteSpace = true;
// test values
$name = 'Test';
$content = '<div onclick="alert(\'Hello!\');">Test div</div>';
// create <html>, <head>, <title> and <body> tags
$html = $dom->createElement( 'html' );
$head = $dom->createElement( 'head' );
$title = $dom->createElement( 'title' );
$body = $dom->createElement( 'body' );
// title text
$titleText = $dom->createTextNode( $name );
// import the text in a new dom
$dom1 = new DOMDocument( '1.0' );
$dom1->formatOutput = true;
$dom1->preserveWhiteSpace = true;
$bodyText = $dom1->loadHTML( $content );
$bodyText = $dom1->getElementsByTagName('body')->item(0);
// add them to the dom
$html = $dom->appendChild( $html );
$html->appendChild( $head );
$head->appendChild( $title );
$title->appendChild( $titleText );
$html->appendChild( $body );
$bodyT = $dom->importNode( $bodyText, true );
$body->appendChild( $bodyT );
echo $dom->saveHTML();
?>
Hope this helps.