Insert HTML into PHP DOM object

Problem

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);
$dom->appendChild($field_div);

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

Solution

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_html->appendXML($field);
$field_div = $dom->createElement(“div”);
$field_div->appendChild($field_html);

source: http://stackoverflow.com/questions/2255158/how-do-i-insert-html-into-a-php-dom-object
keywords: php domnode create node from html string

Tagged with:

Leave a Reply