Home  >  Article  >  Backend Development  >  How to append HTML to a PHP DOMNode without encoding?

How to append HTML to a PHP DOMNode without encoding?

Susan Sarandon
Susan SarandonOriginal
2024-11-19 14:20:03870browse

How to append HTML to a PHP DOMNode without encoding?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn