Home  >  Article  >  Backend Development  >  How to Insert HTML into PHP DOMNodes Without Encoding?

How to Insert HTML into PHP DOMNodes Without Encoding?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-21 04:56:08921browse

How to Insert HTML into PHP DOMNodes Without Encoding?

Inserting HTML into PHP DOMNodes Without Encoding

Inserting HTML into existing DOMNodes without content encoding can be achieved using the DOMDocumentFragment::appendXML method. Here's how:

Example

// DOMDocument setup
$dom = new DOMDocument;
$dom->loadXml('<html><body/></html>');
$body = $dom->documentElement->firstChild;

// Create DocumentFragment for template
$template = $dom->createDocumentFragment();
$template->appendXML('<h1>

Output

<?xml version="1.0"?>
<html><body><h1>

Importing from Another DOMDocument

If you need to import HTML from another DOMDocument, you can use the following code:

// Create new DOMDocument for template
$tpl = new DOMDocument;
$tpl->loadXml('<h1>

Importing Malformed HTML

To import malformed HTML, use loadHTML instead of loadXml and enable internal error handling:

libxml_use_internal_errors(true);
$tpl = new DOMDocument;
$tpl->loadHtml('<h1>

The above is the detailed content of How to Insert HTML into PHP DOMNodes 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