为什么 PHP DOMDocument loadHTML 不适用于波斯语字符?

2024-03-19

这是我的代码 https://3v4l.org/DqZKu:

<?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>&#1587;&#1604;&#1575;&#1605;</p>
.
.

预期输出:

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

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

Note:正如你所看到的,我用过mb_convert_encoding($data, 'HTML-ENTITIES', 'UTF-8')使其正确(基于这个答案 https://stackoverflow.com/questions/8218230/php-domdocument-loadhtml-not-encoding-utf-8-correctly#8218649)但仍然不起作用。


波斯语字符被编码为数字字符引用。它们会正确地显示在浏览器中,或者您可以通过使用以下命令解码它们来查看原始内容html_entity_decode(), e.g.:

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

outputs:

سلام

如果您更喜欢输出中的原始字符而不是数字字符引用,您可以更改:

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>

Example. https://3v4l.org/A3Ck1

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么 PHP DOMDocument loadHTML 不适用于波斯语字符? 的相关文章