Incorporating HTML into a PHP DOMNode
In certain situations, it becomes necessary to embed HTML content within an existing DOMNode without incurring the risk of content encoding. To facilitate this process, PHP provides the DOMDocumentFragment::appendXML method.
Example:
// Establishing a DOM $dom = new DOMDocument; $dom->loadXml('<html><body/></html>'); $body = $dom->documentElement->firstChild; // Creating an HTML fragment $template = $dom->createDocumentFragment(); $template->appendXML('<h1 title="">This is my amazing template</h1>'); $body->appendChild($template); // Displaying the final document echo $dom->saveXml();
Output:
<?xml version="1.0"?> <html><body><h1 title="">This is my amazing template</h1></body></html>
Importing from Another DOMDocument:
To seamlessly incorporate nodes from a separate DOMDocument, consider the following code instead:
// Loading HTML into a separate document $tpl = new DOMDocument;
The above is the detailed content of How can I embed HTML content within a PHP DOMNode without encoding issues?. For more information, please follow other related articles on the PHP Chinese website!