如何使用PHP DOMDocument打印未转义的HTML

时间:2013-12-21 18:20:01

标签: php html

我在JQuery& amp;中有一个简单的,本地运行的应用程序允许用户打开文件,重新排列其DOM元素,然后使用重新排列的元素生成新文件的PHP。问题是PHP DOMDocument正在打印转义的HTML。我需要将POST作为#newfile收到的$content的内容打印为未转义的HTML。

POST功能如下所示:

   $("#submit").click(function() {
     var str = $('#newfile').html();
     $.post("generate.php", { content: str} );
  });

generate.php文件如下所示:

 <?php
 $content = $_POST['content'];

 $doc = new DOMDocument('1.0');

 $doc->formatOutput = true;

 $root = $doc->createElement('html');
 $root = $doc->appendChild($root);

 $head = $doc->createElement('head');
 $head = $root->appendChild($head);

 $body = $doc->createElement('body');
 $body = $root->appendChild($body);

 $element = $doc->createElement('div', $content);
 $element = $body->appendChild($element);

 echo 'Wrote: ' . $doc->saveHTMLFile("output/test.html") . ' bytes';

 ?> 

输出目前是格式良好的HTML文档,但我需要的内容是转义的:

 <html>
 <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
 <body><div>
        &lt;div class="page"&gt;
            &lt;h3&gt;1. Definition&lt;/h3&gt;
            &lt;div id="definition" class="output ui-droppable"&gt;
            &lt;/div&gt;
        &lt;/div&gt;
 </div></body></html>

如何将$ content打印为未转义的HTML?

2 个答案:

答案 0 :(得分:0)

html_entity_decode()与htmlentities()相反,因为它将字符串中的所有HTML实体转换为适用的字符。

    <?php
    $orig = "I'll \"walk\" the <b>dog</b> now";

    $a = htmlentities($orig);

    $b = html_entity_decode($a);

    echo $a; // I'll &quot;walk&quot; the &lt;b&gt;dog&lt;/b&gt; now

    echo $b; // I'll "walk" the <b>dog</b> now
    ?>

参考:http://www.php.net/html_entity_decode

答案 1 :(得分:0)

我使用方法shown in this answer - createDocumentFragment + appendXML。我的最终generate.php看起来像这样,效果很好:

<?php
$content = $_POST['content'];

$doc = new DOMDocument('1.0');
$doc->formatOutput = true;

$root = $doc->createElement('html');
$root = $doc->appendChild($root);

$head = $doc->createElement('head');
$head = $root->appendChild($head);

$body = $doc->createElement('body');
$body = $root->appendChild($body);

$f = $doc->createDocumentFragment();
$f->appendXML($content);
$body->appendChild($f);

echo 'Wrote: ' . $doc->saveHTMLFile("output/test.html") . ' bytes'; // Wrote: 129 bytes

?>