How can I embed HTML content within a PHP DOMNode without encoding issues?

DDD
Release: 2024-11-19 07:48:02
Original
847 people have browsed it

How can I embed HTML content within a PHP DOMNode without encoding issues?

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

Output:

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template