2015-09-23 25 views
1

我有一个PHP文件用于生成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?

+0

你可以'str_replace'呢?创建一个你需要的所有值的数组。与bbcode相同的原理 –

+0

'$ document'对象是什么? – Inurosen

+0

@启动'$ document = new DomDocument;' –

回答

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

你可以试试这个:

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

因为我不想直接在页面上输出文本,而是想将它存储在一个变量中,我不认为我可以使用'echo'。 –

+0

所以你也可以将它存储在一个php变量中,并且只要你想使用,那么你就可以。 – sumitjainjr

1

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

要使用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); 
+0

这工作,谢谢。这比我希望的更详细一些(我希望能够使用HEREDOC来处理多行HTML文本),所以在我接受这个作为正确答案之前,我想检查是否有办法做到这一点代替。 –

相关问题