This is ALL PHP 5 functionality
<?php
// load our html page into a DOM
$pageDOM = DOMDocument::loadHTML("[html template as string]");
// OR load from a file
$pageDOM = DOMDocument::loadHTMLFile("[filepath]");
// load our html snippet into a DOM
// this may have been calculated or retrieved from a database, etc
$snippetDOM = DOMDocument::loadHTML("<h2>Hello</h2>");
// we now can import the snippet into the Page DOM
// PREVIOUS METHOD
// to append the snippet DOM root node, we would use
// $snippetNode = $snippetDOM->documentElement;
// BUT this gives us the nested <html><body> tags
// SOLUTION
// instead of appending the document element of the snippet
// we need to transverse the DOM to get the first (and only) child node of the <body>
$xpath = "/html/body/child::node()[1]";
$DOMXPath1 = new DOMXPath($snippetDOM);
$snippetNode = $DOMXPath->query($xpath)->item(0);
// we now have a reference to the snippet!
//locate the target node in the page DOM
$DOMXPath2 = new DOMXPath($pageDOM);
$targetNode = $DOMXPath2->query("xpath to node to append snippet")->item(0);
// import our snippet node into this DOM
$importedSnippetNode = $pageDOM->importNode($snippetNode, true);
// and append to our child
$targetNode->appendChild($importedSnippetNode);
//flush page DOM to browser
echo $pageDOM->saveHTML();
?>