如何将PHP字符串作为HTML读取

时间:2015-09-23 13:25:58

标签: php html escaping html-entities htmlspecialchars

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

$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?

3 个答案:

答案 0 :(得分:1)

你可以试试这个:

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

答案 1 :(得分:1)

<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);

答案 2 :(得分:1)

所以我找到了我正在寻找的东西:

$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");