PHP中的mb_convert_encoding與iconv函數介紹

mb_convert_encoding這個函數是用來轉換編碼的。原來一直對程序編碼這一律念不理解,不過如今好像有點開竅了。 不過英文通常不會存在編碼問題,只有中文數據纔會有這個問題。好比你用Zend Studio或Editplus寫程序時,用的是gbk編碼,若是數據須要入數據庫,而數據庫的編碼爲utf8時,這時就要把數據進行編碼轉換,否則進到數據庫就會變成亂碼。 mb_convert_encoding的用法見官方: http://cn.php.net/manual/zh/function.mb-convert-encoding.php 作一個GBK To UTF-8 < ?php header("content-Type: text/html; charset=Utf-8"); echo mb_convert_encoding("妳係個人友仔", "UTF-8", "GBK"); ?> 再來個GB2312 To Big5 < ?php header("content-Type: text/html; charset=big5"); echo mb_convert_encoding("你是個人朋友", "big5", "GB2312"); ?> 不過要使用上面的函數須要安裝可是須要先enable mbstring 擴展庫。 PHP中的另一個函數iconv也是用來轉換字符串編碼的,與上函數功能類似。 下面還有一些詳細的例子: iconv — Convert string to requested character encoding (PHP 4 >= 4.0.5, PHP 5) mb_convert_encoding — Convert character encoding (PHP 4 >= 4.0.6, PHP 5) 用法: 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. 使用: 發現iconv在轉換字符」—」到gb2312時會出錯,若是沒有ignore參數,全部該字符後面的字符串都沒法被保存。無論怎麼樣,這個」—」都沒法轉換成功,沒法輸出。 另外mb_convert_encoding沒有這個bug. 通常狀況下用 iconv,只有當遇到沒法肯定原編碼是何種編碼,或者iconv轉化後沒法正常顯示時才用mb_convert_encoding 函數. from_encoding is specified by character code name before conversion. it can be array or string - comma separated enumerated list. If it is not specified, the internal encoding will be used. /* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */ $str = mb_convert_encoding($str, 「UCS-2LE」, 「JIS, eucjp-win, sjis-win」); /* 「auto」 is expanded to 「ASCII,JIS,UTF-8,EUC-JP,SJIS」 */ $str = mb_convert_encoding($str, 「EUC-JP」, 「auto」); 例子: $content = iconv(」GBK」, 「UTF-8″, $content); $content = mb_convert_encoding($content, 「UTF-8″, 「GBK」);
相關文章
相關標籤/搜索