PHP nodeValue剥离html标签 - innerHTML替代? [英] PHP nodeValue strips html tags - innerHTML alternative?
本文介绍了PHP nodeValue剥离html标签 - innerHTML替代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用以下脚本来轻量级的DOM编辑器。但是,中的
nodeValue
正在将我的html标签转换为纯文本。
I'm using the following script for a lightweight DOM editor. However, nodeValue
in my for
loop is converting my html tags to plain text. What is a PHP alternative to nodeValue
that would maintain my 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);
推荐答案
由于 $ edits [$ i]
是一个字符串,您需要将其解析为DOM结构,并使用新结构替换原始内容。
Since $edits[$i]
is a string, you need to parse it into a DOM structure and replace the original content with the new structure.
下面的代码片段使用非XML兼容的HTML做了不可思议的工作。 (例如 HTML 4/5)
The code fragment below does an incredible job when using non-XML compliant HTML. (e.g. 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替代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文