問題描述
我正在嘗試使用 DOMDocument 解析一些 HTML,但是當(dāng)我這樣做時,我突然丟失了我的編碼(至少在我看來是這樣).
I'm trying to parse some HTML using DOMDocument, but when I do, I suddenly lose my encoding (at least that is how it appears to me).
$profile = "<div><p>various japanese characters</p></div>";
$dom = new DOMDocument();
$dom->loadHTML($profile);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
echo $dom->saveHTML($div);
}
這段代碼的結(jié)果是我得到了一堆不是日語的字符.但是,如果我這樣做:
The result of this code is that I get a bunch of characters that are not Japanese. However, if I do:
echo $profile;
顯示正確.我試過 saveHTML 和 saveXML,但都不能正確顯示.我使用的是 PHP 5.3.
it displays correctly. I've tried saveHTML and saveXML, and neither display correctly. I am using PHP 5.3.
我所看到的:
?¤?a??¤?·?·???′???|??¢?¤?????3??3???????o-???9?oo?????5?a???¨??|??????????????|4?oo???3?a???a?£????è|a?ˉ?¨??????????1??3?§??ˉè|a?ˉéμ????±????¢??¤??? ?£??é?? ????£?ˉ?-?£??£???¢????¤????¤?????è2è3é????a??????a??ˉ?3???é?? ???é2?-|?
應(yīng)該顯示什么:
イリノイ州シカゴにて、アイルランド系の家庭に、9人兄弟の5番目として生まれる。彼を含めて4人が俳優(yōu)になった。父親は木材のセールスマンで、母親は郵便局の客室係だった。高校時代はキャディのアルバイトに勤しみ、教育資金を受けながらカトリック系の高校へ進學(xué)
我已將代碼簡化為五行,以便您可以自行測試.
I've simplified the code down to five lines so you can test it yourself.
$profile = "<div lang=ja><p>イリノイ州シカゴにて、アイルランド系の家庭に、</p></div>";
$dom = new DOMDocument();
$dom->loadHTML($profile);
echo $dom->saveHTML();
echo $profile;
這是返回的html:
<div lang="ja"><p>??¤??a?????¤?·???·?????′???|?€??¢??¤????????3??‰?3???????o-???€</p></div>
<div lang="ja"><p>イリノイ州シカゴにて、アイルランド系の家庭に、</p></div>
推薦答案
DOMDocument::loadHTML
會將您的字符串視為 ISO-8859-1 中的字符串,除非您另有說明.這會導(dǎo)致 UTF-8 字符串被錯誤解釋.
DOMDocument::loadHTML
will treat your string as being in ISO-8859-1 unless you tell it otherwise. This results in UTF-8 strings being interpreted incorrectly.
如果您的字符串不包含 XML 編碼聲明,您可以在前面加上一個,使字符串被視為 UTF-8:
If your string doesn't contain an XML encoding declaration, you can prepend one to cause the string to be treated as UTF-8:
$profile = '<p>イリノイ州シカゴにて、アイルランド系の家庭に、9</p>';
$dom = new DOMDocument();
$dom->loadHTML('<?xml encoding="utf-8" ?>' . $profile);
echo $dom->saveHTML();
如果你不知道字符串是否已經(jīng)包含這樣的聲明,在 SmartDOMDocument 應(yīng)該可以幫助您:
If you cannot know if the string will contain such a declaration already, there's a workaround in SmartDOMDocument which should help you:
$profile = '<p>イリノイ州シカゴにて、アイルランド系の家庭に、9</p>';
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8'));
echo $dom->saveHTML();
這不是一個很好的解決方法,但由于并非所有字符都可以在 ISO-8859-1 中表示(如這些武士刀),因此它是最安全的替代方法.
This is not a great workaround, but since not all characters can be represented in ISO-8859-1 (like these katana), it's the safest alternative.
這篇關(guān)于PHP DOMDocument loadHTML 未正確編碼 UTF-8的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!