为什么PHP DOMDocument的loadHTML函数不能处理波斯语字符?

4

这是我的代码

<?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();

作为我的问题标题中提到的,我的网站内容是波斯语(非英语)。但是关于代码对波斯字符不起作用。

当前输出:

.
.
    <p>&#1587;&#1604;&#1575;&#1605;</p>
.
.

期望输出:

.
.
    <p>سلام</p>
.
.

这是什么问题,我该如何修复它?

注意:您也可以看到我已经使用了mb_convert_encoding($data, 'HTML-ENTITIES', 'UTF-8')来使其正确显示(基于此答案),但仍然无法解决问题。

1个回答

3

波斯语字符被编码为数字字符引用。它们将在浏览器中正确显示,或者您可以使用html_entity_decode()解码查看原始内容,例如:

echo html_entity_decode("&#1587;&#1604;&#1575;&#1605;");

输出:

سلام

如果您希望输出中使用原始字符而不是数字字符引用,可以更改以下设置:
echo $dom->saveHTML();

to:

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>

示例。


谢谢,你帮了我很多。 - Raz Galstyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接