如何将 PHP 字符串读作 HTML

How to read a PHP string as HTML

我有一个 PHP 文件用于生成 HTML 文件。这是过程:

$document = new DomDocument;
$document->preserveWhiteSpace = false;
$document->validateOnParse = true;
$document->loadHTML(file_get_contents("http://www.example.com/base.html"));

$testNode = $document->createElement("div", "This is a <br> test");
$document->appendChild($testNode);

$document->saveHTMLFile("output.html");

这将生成一个包含以下元素的 HTML 文件:

<div>This is a &lt;br&gt; test</div>

也就是说,<br> 标签在实际 HTML 中被转换为 &lt;br&gt;。我已经尝试了所有这些方法来取消转义字符串:

htmlspecialchars("This is a <br> test");

rawurldecode("This is a <br> test");

urldecode("This is a <br> test");

function decodeashtml($str) {
$str = preg_replace("/%u([0-9a-f]{3,4})/i","&#x\1;",urldecode($str));
return html_entity_decode($str,null,'UTF-8');;
}
decodeashtml("This is a <br> test");

但它们都产生:

This is a &lt;br&gt; test

我还能做些什么来让 HTML 标签正确显示为 HTML?

你可以试试这个:

<?php echo html_entity_decode("this is <br> test."); ?>

<p>This is a <br /> test</p> 是一个 p 元素,包含一个文本节点、一个 br 元素和另一个文本节点。

要与 PHP 的 XML 作者一起正确执行此操作:

$element = $document->createElement('p');

$element->appendChild($document->createTextNode('This is a '));
$element->appendChild($document->createElement('br'));
$element->appendChild($document->createTextNode(' test'));

$document->appendChild($element);

所以我找到了我要找的东西:

$document = new DomDocument;
$document->preserveWhiteSpace = false;
$document->validateOnParse = true;
$document->loadHTML(file_get_contents("http://www.example.com/base.html"));

$newDiv = $document->createElement("div");
$fragment = $document->createDocumentFragment();
$fragment->appendXML("<p>I can write<br/>my HTML here.</p>");
$newDiv->appendChild($fragment);

$document->appendChild($newDiv);

$document->saveHTMLFile("output.html");