Home  >  Article  >  Backend Development  >  How to Integrate HTML Templates into PHP DOMNodes While Preserving Raw HTML Content?

How to Integrate HTML Templates into PHP DOMNodes While Preserving Raw HTML Content?

Barbara Streisand
Barbara StreisandOriginal
2024-11-09 17:27:02768browse

How to Integrate HTML Templates into PHP DOMNodes While Preserving Raw HTML Content?

Integrating HTML Templates into PHP DOMNodes

Integrating HTML templates into existing PHP DOMNodes can be challenging, especially if you desire to preserve the raw HTML content.

Native PHP Solutions

PHP provides a few native methods to achieve this:

  • DOMDocumentFragment::appendXML: Appends raw XML data to a DOM DocumentFragment.

Example:

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

$template = $dom->createDocumentFragment();
$template->appendXML('<h1>

Output:

<html><body><h1>
  • DOMDocument::importNode: Imports a node from another DOMDocument.

Example for Importing from Another DOMDocument:

$tpl = new DOMDocument;
$tpl->loadXml('<h1>
  • DOMDocument::loadHTML: Loads HTML markup, triggering libxml's parser for potentially malformed HTML.

Example:

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

Note:

In all these methods, using TRUE as the second argument to importNode imports the node and its entire subtree.

The above is the detailed content of How to Integrate HTML Templates into PHP DOMNodes While Preserving Raw HTML Content?. 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