下面是我的代码:
<?php
$data = <<<DATA
<div>
<p>سلام</p> // focus on this line
<p class="myclass">Remove this one</p>
<p>But keep this</p>
<div style="color: red">and this</div>
<div style="color: red">and <p>also</p> this</div>
<div style="color: red">and this <div style="color: red">too</div></div>
</div>
DATA;
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($data, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//*[@*]") as $node) {
$parent = $node->parentNode;
while ($node->hasChildNodes()) {
$parent->insertBefore($node->lastChild, $node->nextSibling);
}
$parent->removeChild($node);
}
echo $dom->saveHTML();
正如我在问题标题中提到的,我网站的内容是波斯语(不是英语)。但是about代码对波斯语字符不起作用。
当前输出:.
.
<p>سلام</p>
.
.
预期输出:.
.
<p>سلام</p>
.
.
有什么问题,我该怎么解决?
注意:也正如你所看到的,我已经使用mb_convert_encoding($data, 'HTML-ENTITIES', 'UTF-8')
使其正确(基于此答案)但仍然不起作用
波斯语字符被编码为数字字符引用。它们将在浏览器中适当地显示,或者您可以通过使用html_entity_decode()
解码来查看原始内容,例如:
echo html_entity_decode("سلام");
输出:
سلام
如果您更喜欢输出中的原始字符而不是数字字符引用,则可以更改:
echo $dom->saveHTML();
:
echo $dom->saveHTML($dom->documentElement);
这将序列化改变一个位,结果是:
<div>
<p>سلام</p>
Remove this one
<p>But keep this</p>
and this
and <p>also</p> this
and this too
</div>
。