[英]PHP nodeValue strips html tags - innerHTML alternative?
I'm using the following script for a lightweight DOM editor. 我正在使用以下脚本进行轻量级DOM编辑器。 However, nodeValue
in my for
loop is converting my html tags to plain text. 但是,我的for
循环中的nodeValue
将我的html标签转换为纯文本。 What is a PHP alternative to nodeValue
that would maintain my innerHTML? 什么是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);
Since $edits[$i]
is a string, you need to parse it into a DOM structure and replace the original content with the new structure. 由于$edits[$i]
是一个字符串,因此您需要将其解析为DOM结构并用新结构替换原始内容。
The code fragment below does an incredible job when using non-XML compliant HTML. 下面的代码片段在使用非XML兼容的HTML时做了不可思议的工作。 ( eg HTML 4/5) ( 例如 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));
}
}
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. 我以前没有在PHP中使用该库,但在我的其他xpath体验中,我认为除文本节点之外的任何节点上的nodeValue都会剥离标记。 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. 如果您不确定该节点下面的内容,那么我认为如果需要返回标记,则需要递归下降$ entries-> item($ i) - > childNodes。
Or...you may wany textContent instead of nodeValue: http://us.php.net/manual/en/class.domnode.php#domnode.props.textcontent 或者......你可能会使用textContent而不是nodeValue: http ://us.php.net/manual/en/class.domnode.php#domnode.props.textcontent
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.