2012-07-26 72 views
9

我正在構建一個PHP Web應用程序,它以UTF-8工作。數據庫是UTF-8,頁面作爲UTF-8提供,我使用元標記將字符集設置爲UTF-8。當然,對於使用Internet Explorer的用戶,以及從Microsoft Office複製粘貼&,我以某種方式設法不偶爾地獲取UTF-8輸入。將用戶輸入轉換爲UTF-8的最佳方法

理想的解決方案是拋出HTTP 400 Bad Request錯誤,但顯然我不能那樣做。次好的是將$_GET,$_POST$_REQUEST轉換爲UTF-8。無論如何看看什麼字符編碼的輸入是在所以我可以傳遞給iconv?如果不是,這樣做的最佳解決方案是什麼?

回答

8

退房mb_detect_encoding()例:

$utf8 = iconv(mb_detect_encoding($input), 'UTF-8', $input); 

還有utf8_encode()如果你保證字符串輸入爲ISO-8859-1。

+0

顯然不能保證字符串是ISO-8859-1,但'mb_detect_encoding()'看起來不錯 – 2012-07-26 14:29:54

0

在某些情況下,僅使用utf8_encode或一般檢查即可,但可能會丟失字符串中的某些字符。如果你可以建立一個基於不同類型的基本數組/字符串列表,這個例子是windows,你可以挽救更多。

if(!mb_detect_encoding($fileContents, "UTF-8", true)){ 
    $checkArr = array("windows-1252", "windows-1251"); 
    $encodeString = ''; 
    foreach($checkArr as $encode){ 
     if(mb_check_encoding($fileContents, $encode)){ 
      $encodeString .= $encode.","; 
     } 
    } 
    $encodeString = substr($encodeString, 0, -1); 
    $fileContents = mb_convert_encoding($fileContents, "UTF-8", $encodeString); 
} 
相關問題