標籤:
漢字亂碼真是一個悲催的事情,JAVA討厭漢字,PHP也不喜歡漢字;
Java亂碼最終使用了spring給出的過濾器來過濾,處處過濾,其實影響了速度,不過沒有辦法,漢字就是W國首先不考慮的事情;
想不到PHP也是亂碼處處在,當你使用親兄弟MySQL的時候,漢字顯得那麼親切,從未考慮過他會變成天書;不過為了和其他其他互動,把PHP的手伸到SQL SERVER的時候,亂碼來了,原因是第三方系統用的GBK編碼;
哎,轉換吧;
1,PHP內建的轉換函式ICONV,一個高大上的函數;
string iconv ( string $in_charset , string $out_charset , string $str )
使用DEMO:
<?php$text = "This is the Euro symbol ‘€‘.";echo ‘Original : ‘, $text, PHP_EOL;echo ‘TRANSLIT : ‘, iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL;echo ‘IGNORE : ‘, iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL;echo ‘Plain : ‘, iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL;?>
大家都推薦的函數,不過使用之後無法轉換,沒有錯誤,字元也沒有轉換,NO!
2,另闢蹊徑,還有一個大家質疑效率不高的函數,不過無論如何,先實現再考慮其他三
//檢查該函數是否可用echo function_exists(‘mb_convert_encoding‘);//檢測當前編碼echo mb_detect_encoding($val, "GBK, GB2312, UTF-8");//轉換編碼,把CP936(就是GBK)轉換成UTF-8$v=mb_convert_encoding ($val, "UTF-8", "CP936");
結果成功了;
好吧,先用著吧,為了轉換資料庫查詢的結果集,製作一個轉換函式:
1,函數“亂碼剋星”:
// $fContents 字串// $from 字串的編碼// $to 要轉換的編碼function auto_charset($fContents,$from=‘gbk‘,$to=‘utf-8‘){ $from = strtoupper($from)==‘UTF8‘? ‘utf-8‘:$from; $to = strtoupper($to)==‘UTF8‘? ‘utf-8‘:$to; if( strtoupper($from) === strtoupper($to) || empty($fContents) || (is_scalar($fContents) && !is_string($fContents)) ){ //如果編碼相同或者非字串標量則不轉換 return $fContents; } if(is_string($fContents) ) { if(function_exists(‘mb_convert_encoding‘)){ return mb_convert_encoding ($fContents, $to, $from); }else{ return $fContents; } } elseif(is_array($fContents)){ foreach ( $fContents as $key => $val ) { $_key = auto_charset($key,$from,$to); $fContents[$_key] = auto_charset($val,$from,$to); if($key != $_key ) unset($fContents[$key]); } return $fContents; } else{ return $fContents; }}
2,使用:
//列印輸出查詢結果(假設你的結果)$arr=array();while($list=mssql_fetch_row($row)){$arr[]=$list;}$s=auto_charset($arr,‘gbk‘,‘utf-8‘);//列印試試,在瀏覽器設定編碼為UFT-8,看沒有亂碼print_r($s);die();
PHP也有萬惡的中文亂碼,解決方案