Insert HTML into PHP DOM object


I recently had an html string that needed to be added to a DOM object.   At first I had something like this:

$dom = new DOMDocument;
$field_div = $dom->createElement(“div”, $field);

Where $field was an html string.  This produced a div with the html printed out as text.


Stack overflow is just the best website ever created for developers.  The solution is to use DOM->createDocumentFragment.  So the new code looked like:

$field_html = $dom->createDocumentFragment(); // create fragment
$field_div = $dom->createElement(“div”);

keywords: php domnode create node from html string

Tagged with:

Leave a Reply

Your email address will not be published. Required fields are marked *


This site uses Akismet to reduce spam. Learn how your comment data is processed.