PHP也有萬惡的中文亂碼,解決方案

來源:互聯網
上載者:User

標籤:

    漢字亂碼真是一個悲催的事情,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也有萬惡的中文亂碼,解決方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.