PHP中文亂碼解決方案
漢字亂碼真是一個悲催的事情,JAVA討厭漢字,PHP也不喜歡漢字;
Java亂碼最終使用了spring給出的過濾器來過濾,處處過濾,其實影響了速度,不過沒有辦法,漢字就是W國首先不考慮的事情;
想不到PHP也是亂碼處處在,當你使用親兄弟MySQL的時候,漢字顯得那么親切,從未考慮過他會變成天書;不過為了和其他其他交互,把PHP的手伸到SQL SERVER的時候,亂碼來了,原因是第三方系統(tǒng)用的GBK編碼;
哎,轉換吧;
1,PHP自帶的轉換函數(shù)ICONV,一個高大上的函數(shù);
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;
?>
大家都推薦的函數(shù),不過使用之后無法轉換,沒有錯誤,字符也沒有轉換,NO!
2,另辟蹊徑,還有一個大家質(zhì)疑效率不高的函數(shù),不過無論如何,先實現(xiàn)再考慮其他三
//檢查該函數(shù)是否可用
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");
結果成功了;
好吧,先用著吧,為了轉換數(shù)據(jù)庫查詢的結果集,制作一個轉換函數(shù):
1,函數(shù)“亂碼克星”:
// $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中文亂碼的介紹了,希望大家能夠喜歡。
相關文章
PHP基于session.upload_progress 實現(xiàn)文件上傳進度顯示功能詳解
這篇文章主要介紹了PHP基于session.upload_progress 實現(xiàn)文件上傳進度顯示功能,結合實例形式分析了php5.4版本session.upload_progress特性實現(xiàn)文件上傳進度顯示的相關操作技巧,需要的朋友可以參考下2019-08-08詳解WordPress中用于更新和獲取用戶選項數(shù)據(jù)的PHP函數(shù)
這篇文章主要介紹了WordPress中用于更新和獲取用戶選項數(shù)據(jù)的PHP函數(shù),分別為對update_user_option()函數(shù)和get_user_option()函數(shù)用法的講解,需要的朋友可以參考下2016-03-03