PHP DOMDocument replace DOMElement child with HTML string

后端 未结 5 1617
[愿得一人]
[愿得一人] 2020-12-31 13:09

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.

5条回答
  •  盖世英雄少女心
    2020-12-31 13:51

    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 = '

    bar

    '; // 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

提交回复
热议问题