{"id":841,"date":"2012-08-30T15:50:45","date_gmt":"2012-08-31T01:50:45","guid":{"rendered":"http:\/\/mymonkeydo.com\/?p=841"},"modified":"2012-08-30T15:50:45","modified_gmt":"2012-08-31T01:50:45","slug":"insert-html-into-php-dom-object","status":"publish","type":"post","link":"https:\/\/mymonkeydo.com\/insert-html-into-php-dom-object\/","title":{"rendered":"Insert HTML into PHP DOM object"},"content":{"rendered":"
I recently had an html string that needed to be added to a DOM object. \u00a0 At first I had something like this:<\/p>\n
$dom = new DOMDocument;
\n$field_div = $dom->createElement(“div”, $field);
\n$dom->appendChild($field_div);<\/p>\n
Where $field was an html string. \u00a0This produced a div with the html printed out as text.<\/p>\n
Stack overflow is just the best website ever created for developers. \u00a0The solution is to use DOM->createDocumentFragment. \u00a0So the new code looked like:<\/p>\n
$field_html = $dom->createDocumentFragment(); \/\/ create fragment
\n$field_html->appendXML($field);
\n$field_div = $dom->createElement(“div”);
\n$field_div->appendChild($field_html);<\/p>\n