views:

546

answers:

2

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.

So far I'm loading the document identifying the element I want to change by ID but the process to convert an HTML to something that can be placed inside a DOMElement is eluding me.

libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->loadHTML($html);

$element = $doc->getElementById($item_id);
if(isset($element)){
    //Remove the old children from the element
    while($element->childNodes->length){
        $element->removeChild($element->firstChild);
    }

    //Need to build the new children from $html_string and append to $element
}
A: 

You can use loadHTML() on a fragment of code and then append the resulting created nodes into the original DOM tree.

Amber
Would you be suggesting creating a new DOMDocument using load HTML then taking the children of the new Document's body tag and appending them to the orginal DOM? Or is there another loadHTML() function I'm missing.
AWinter
I really hate how html and body tags are added automatically when you do things like saveHTML() or loadHTML(). Is there an easy workaround other than writing a wrapper that would strip them off?
Artem Russakovskii
+1  A: 
Keyvan