Inserting HTML into PHP DOMNode
To append HTML to an existing DOMNode without encoding, utilize DOMDocumentFragment::appendXML.
// DOM setup $dom = new DOMDocument; $dom->loadXML('<html><body/></html>'); $body = $dom->documentElement->firstChild; // Append HTML fragment $template = $dom->createDocumentFragment(); $template->appendXML('<h1>This is <em>my</em> template</h1>'); $body->appendChild($template); // Output echo $dom->saveXml();
Output:
<?xml version="1.0"?> <html><body><h1>This is <em>my</em> template</h1></body></html>
Importing from Another DOMDocument
// Load another DOMDocument $tpl = new DOMDocument; $tpl->loadXML('<h1>This is <em>my</em> template</h1>'); // Import and append $body->appendChild($dom->importNode($tpl->documentElement, TRUE));
Importing Malformed HTML
// Enable libxml error handling libxml_use_internal_errors(true); // Load and import HTML $tpl = new DOMDocument; $tpl->loadHtml('<h1>This is <em>malformed</em> template</h1></h2>'); $body->appendChild($dom->importNode($tpl->documentElement, TRUE)); // Disable libxml error handling libxml_use_internal_errors(false);
The above is the detailed content of How to append HTML to a PHP DOMNode without encoding?. For more information, please follow other related articles on the PHP Chinese website!