PHP nodeValue 剥离 html 标签 - innerHTML 替代方案?
我将以下脚本用于轻量级 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);
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);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
由于
$edits[$i]
是一个字符串,因此需要将其解析为 DOM 结构,并用新结构替换原来的内容。更新
当使用非 XML 兼容的 HTML 时,下面的代码片段做了令人难以置信的工作。 (例如 HTML 4/5)
Since
$edits[$i]
is a string, you need to parse it into a DOM structure and replace the original content with the new structure.Update
The code fragment below does an incredible job when using non-XML compliant HTML. (e.g. HTML 4/5)
我以前没有在 PHP 中使用过该库,但根据我的其他 xpath 经验,我认为除文本节点之外的任何节点上的 nodeValue 都会删除标签。如果您不确定该节点下面的内容,那么我认为如果您需要恢复标记,则需要递归地下降 $entries->item($i)->childNodes 。
或者...您可能想要 textContent 而不是 nodeValue:
http://us.php.net/manual/en /class.domnode.php#domnode.props.textcontent
I haven't working with that library in PHP before, but in my other xpath experience I think that nodeValue on anything other than a text node does strip tags. If you're unsure about what's underneath that node, then I think you'll need to recursively descend $entries->item($i)->childNodes if you need to get the markup back.
Or...you may wany textContent instead of nodeValue:
http://us.php.net/manual/en/class.domnode.php#domnode.props.textcontent