我正在为轻量级 DOM 编辑器使用以下脚本。但是,我的 for
循环中的 nodeValue
正在将我的 html 标签转换为纯文本。什么是可以维护我的 innerHTML 的 nodeValue
PHP 替代品?
$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);
最佳答案
由于$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));
}
}
关于PHP nodeValue 剥离 html 标签 - innerHTML 替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7857595/