Using PHP I\'m attempting to take an HTML string passed from a WYSIWYG editor and replace the children of an element inside of a preloaded HTML document with the new HTML.>
I know this is old, but none of the current answers show a minimal working example of how to replace DOMNode(s) in a DOMDocument with an HTML stored in a string.
// the HTML fragment we want to use as the replacement
$htmlReplace = 'foo';
// the HTML of the original document
$htmlHaystack = '';
// load the HTML replacement fragment
$domDocumentReplace = new \DOMDocument;
$domDocumentReplace->loadHTML($htmlReplace, LIBXML_HTML_NOIMPLIED);
// load the HTML of the document
$domDocumentHaystack = new \DOMDocument;
$domDocumentHaystack->loadHTML($htmlHaystack, LIBXML_HTML_NOIMPLIED);
// import the replacement node into the document
$htmlReplaceNode = $domDocumentHaystack->importNode($domDocumentReplace->documentElement, true);
// find the DOMNode(s) we want to replace - in this case #tag (to keep the example simple)
$domNodeTag = $domDocumentHaystack->getElementById('tag');
// replace the node
$domNodeTag->parentNode->replaceChild($htmlReplaceNode, $domNodeTag);
// output the new HTML of the document
echo $domDocumentHaystack->saveHTML($domDocumentHaystack->documentElement);
// foo