PHP中文亂碼解決方案
漢字亂碼真是一個(gè)悲催的事情,JAVA討厭漢字,PHP也不喜歡漢字;
Java亂碼最終使用了spring給出的過(guò)濾器來(lái)過(guò)濾,處處過(guò)濾,其實(shí)影響了速度,不過(guò)沒(méi)有辦法,漢字就是W國(guó)首先不考慮的事情;
想不到PHP也是亂碼處處在,當(dāng)你使用親兄弟MySQL的時(shí)候,漢字顯得那么親切,從未考慮過(guò)他會(huì)變成天書;不過(guò)為了和其他其他交互,把PHP的手伸到SQL SERVER的時(shí)候,亂碼來(lái)了,原因是第三方系統(tǒng)用的GBK編碼;
哎,轉(zhuǎn)換吧;
1,PHP自帶的轉(zhuǎn)換函數(shù)ICONV,一個(gè)高大上的函數(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ù),不過(guò)使用之后無(wú)法轉(zhuǎn)換,沒(méi)有錯(cuò)誤,字符也沒(méi)有轉(zhuǎn)換,NO!
2,另辟蹊徑,還有一個(gè)大家質(zhì)疑效率不高的函數(shù),不過(guò)無(wú)論如何,先實(shí)現(xiàn)再考慮其他三
//檢查該函數(shù)是否可用
echo function_exists('mb_convert_encoding');
//檢測(cè)當(dāng)前編碼
echo mb_detect_encoding($val, "GBK, GB2312, UTF-8");
//轉(zhuǎn)換編碼,把CP936(就是GBK)轉(zhuǎn)換成UTF-8
$v=mb_convert_encoding ($val, "UTF-8", "CP936");
結(jié)果成功了;
好吧,先用著吧,為了轉(zhuǎn)換數(shù)據(jù)庫(kù)查詢的結(jié)果集,制作一個(gè)轉(zhuǎn)換函數(shù):
1,函數(shù)“亂碼克星”:
// $fContents 字符串
// $from 字符串的編碼
// $to 要轉(zhuǎn)換的編碼
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)) ){
//如果編碼相同或者非字符串標(biāo)量則不轉(zhuǎn)換
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,使用:
//打印輸出查詢結(jié)果(假設(shè)你的結(jié)果)
$arr=array();
while($list=mssql_fetch_row($row))
{
$arr[]=$list;
}
$s=auto_charset($arr,'gbk','utf-8');
//打印試試,在瀏覽器設(shè)置編碼為UFT-8,看沒(méi)有亂碼
print_r($s);die();
以上所述就是本文關(guān)于php中文亂碼的介紹了,希望大家能夠喜歡。
相關(guān)文章
PHP實(shí)現(xiàn)HTTP斷點(diǎn)續(xù)傳的方法
這篇文章主要介紹了PHP實(shí)現(xiàn)HTTP斷點(diǎn)續(xù)傳的方法,實(shí)例分析了php基于http協(xié)議斷點(diǎn)續(xù)傳下載文件的實(shí)現(xiàn)方法,需要的朋友可以參考下2015-06-06

PHP基于session.upload_progress 實(shí)現(xiàn)文件上傳進(jìn)度顯示功能詳解

詳解WordPress中用于更新和獲取用戶選項(xiàng)數(shù)據(jù)的PHP函數(shù)