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

How to append HTML to a PHP DOMNode without encoding?

Susan Sarandon
Release: 2024-11-19 14:20:03
Original
882 people have browsed it

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();
Copy after login

Output:

<?xml version="1.0"?>
<html><body><h1>This is <em>my</em> template</h1></body></html>
Copy after login

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));
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template