1. 程式人生 > >PHP中文GBK編碼轉UTF-8

PHP中文GBK編碼轉UTF-8

iconv 和 mb_convert_encoding的區別

函式比較

string mb_convert_encoding ( string str, string to_encoding [, mixed from_encoding] )
需要先enable mbstring 擴充套件庫,在 php.ini裡將; extension=php_mbstring.dll 前面的 ; 去掉
mb_convert_encoding 可以指定多種輸入編碼,它會根據內容自動識別,但是執行效率比iconv差太多;

string iconv ( string in_charset, string out_charset, string str )
注意:第二個引數,除了可以指定要轉化到的編碼以外,還可以增加兩個字尾://TRANSLIT 和 //IGNORE,其中 //TRANSLIT 會自動將不能直接轉化的字元變成一個或多個近似的字元,//IGNORE 會忽略掉不能轉化的字元,而預設效果是從第一個非法字元截斷。
Returns the converted string or FALSE on failure.

示例

做一個GBK To UTF-8

< ?php 
header("content-Type: text/html; charset=Utf-8"); 
echo mb_convert_encoding("妳係我的友仔", "UTF-8", "GBK"); 
?>
$content = iconv("UTF-8", "GBK//IGNORE",$content);

PHP——字串統一轉碼為GBK,自動判斷是否UTF8並轉碼

public static function strToGBK($strText)
    {
        $encode = mb_detect_encoding($strText, array
('UTF-8','GB2312','GBK')); if($encode == "UTF-8") { return @iconv('UTF-8','GB18030',$strText); } else { return $strText; } }

實戰

$str = "餜槝餜槝";
// $str = "鑼跺崱闀囧嶮瀛楄礬鍙e悜鍖?00綾?楂樺師緹庝附涔℃溈澶ч棬鏃佽竟";
// $new_str = iconv( "gbk","utf-8", $str);


$new_str
= iconv('UTF-8', 'GBK//TRANSLIT', $str); dump($new_str); // iconv("UTF-8", "GBK//IGNORE", $text); echo mb_convert_encoding($str, "GBK", "UTF-8"); dump($str_new); dump($new_str);