【问题标题】:PHP nodeValue strips html tags - innerHTML alternative?PHP nodeValue剥离html标签-innerHTML替代品?
【发布时间】:2011-12-13 01:02:22
【问题描述】:

我将以下脚本用于轻量级 DOM 编辑器。但是,我的for 循环中的nodeValue 正在将我的html 标记转换为纯文本。 nodeValue 的 PHP 替代品是什么,可以维护我的 innerHTML?

$page = $_POST['page'];
$json = $_POST['json'];

$doc = new DOMDocument();
$doc = DOMDocument::loadHTMLFile($page);

$xpath = new DOMXPath($doc);
$entries = $xpath->query('//*[@class="editable"]');
$edits = json_decode($json, true);
$num_edits = count($edits);

for($i=0; $i<$num_edits; $i++) 
{
    $entries->item($i)->nodeValue = $edits[$i]; // nodeValue strips html tags
}

$doc->saveHTMLFile($page);

【问题讨论】:

    标签: php dom domdocument


    【解决方案1】:

    由于$edits[$i]是字符串,需要将其解析成DOM结构,并将原来的内容替换成新的结构。

    更新

    下面的代码片段在使用不符合 XML 的 HTML 时表现出色。 (例如 HTML 4/5)

    for($i=0; $i<$num_edits; $i++)
    {
        $f = new DOMDocument();
        $edit = mb_convert_encoding($edits[$i], 'HTML-ENTITIES', "UTF-8"); 
        $f->loadHTML($edit);
        $node = $f->documentElement->firstChild;
        $entries->item($i)->nodeValue = "";
        foreach($node->childNodes as $child) {
            $entries->item($i)->appendChild($doc->importNode($child, true));
        }
    }
    

    【讨论】:

    • 这感觉有点像作弊,因为我在原始代码上工作,但这是一个很常见的问题,也许其他人会从这篇文章中受益。 :-)
    • 哈哈 - 在您在另一篇文章中回答之前,我已经发布了这个问题:)。再次感谢!值得注意的是,使用 appendXML,我确实必须替换一些特殊字符 .replace(/&amp;nbsp;/gi, "&amp;#160;").replace(/&lt;br&gt;/gi, '&lt;br /&gt;'); 才能正确解析,但一切正常!
    • @Josiah:我想我应该进行更多测试。 :-) 无论如何,我用改进的代码更新了答案,所以你不必求助于replace。它处理 HTML(不是 XML),即使它包含 UTF-8 字符。
    【解决方案2】:

    我以前没有在 PHP 中使用过该库,但在我的其他 xpath 经验中,我认为除了文本节点之外的任何东西上的 nodeValue 都会剥离标签。如果您不确定该节点下的内容,那么我认为如果您需要取回标记,则需要递归下降 $entries->item($i)->childNodes。

    或者...您可以使用 textContent 而不是 nodeValue: http://us.php.net/manual/en/class.domnode.php#domnode.props.textcontent

    【讨论】:

      猜你喜欢
      • 2013-07-11
      • 2011-09-11
      • 1970-01-01
      • 2019-06-07
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 2023-02-23
      • 2010-10-17
      相关资源
      最近更新 更多