我在使用PHP將ISO-8859-1數據庫內容轉換爲UTF-8時遇到了一些問題。我運行下面的代碼進行測試:PHP:從ISO-8859-1到「UTF-8」轉換「'」字符時出現問題
// Connect to a latin1 charset database
// and retrieve "Georgia O’Keeffe", which contains a "’" character
$connection = mysql_connect('*****', '*****', '*****');
mysql_select_db('*****', $connection);
mysql_set_charset('latin1', $connection);
$result = mysql_query('SELECT notes FROM categories WHERE id = 16', $connection);
$latin1Str = mysql_result($result, 0);
$latin1Str = substr($latin1Str, strpos($latin1Str, 'Georgia'), 16);
// Try to convert it to UTF-8
$utf8Str = iconv('ISO-8859-1', 'UTF-8', $latin1Str);
// Output both
var_dump($latin1Str);
var_dump($utf8Str);
當我在Firefox中的源視圖運行它,確保Firefox的編碼設置爲「西方(ISO-8859-1)」,我得到這個:
到目前爲止,這麼好。第一個輸出包含奇怪的引號,我可以正確看到它,因爲它在ISO-8859-1中,Firefox也是如此。
後,我改變Firefox的編碼設置爲 「UTF-8」,它看起來像這樣:
哪裏報價走?是不是iconv()
應該將其轉換爲UTF-8?
哇,我這樣做,我看到U + 2019 UTF-8模式!但是使用「windows-1252」將大量數據從「ISO-8859-1」轉換爲「UTF-8」是否安全?換句話說,所有的ISO-8859-1字符是否仍能正確轉換? – mattalxndr 2010-09-15 01:44:07
字符0x80-0x9F將無法正確轉換。但這些是幾乎從未使用的控制字符。 – dan04 2010-09-15 01:54:29
@mattalexx如果您檢查該字符串中的字符並找到任何字符,則很有可能該字符串是在Windows-1252中編碼的。如果你**沒有找到該範圍內的任何字符,則更可能是ISO-8859-1。 – 2011-06-13 20:27:06