Home > Backend Development > PHP Tutorial > PHP也有万恶的中文乱码,解决方法

PHP也有万恶的中文乱码,解决方法

WBOY
Release: 2016-06-23 13:40:08
Original
917 people have browsed it

    汉字乱码真是一个悲催的事情,JAVA讨厌汉字,PHP也不喜欢汉字;

    Java乱码最终使用了spring给出的过滤器来过滤,处处过滤,其实影响了速度,不过没有办法,汉字就是W国首先不考虑的事情;

    想不到PHP也是乱码处处在,当你使用亲兄弟MySQL的时候,汉字显得那么亲切,从未考虑过他会变成天书;不过为了和其他其他交互,把PHP的手伸到SQL SERVER的时候,乱码来了,原因是第三方系统用的GBK编码;

    哎,转换吧;

   1,PHP自带的转换函数ICONV,一个高大上的函数;

   

string iconv ( string $in_charset , string $out_charset , string $str )
Copy after login

使用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;?>
Copy after login

大家都推荐的函数,不过使用之后无法转换,没有错误,字符也没有转换,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");
Copy after login

结果成功了;

好吧,先用着吧,为了转换数据库查询的结果集,制作一个转换函数:

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;    }}
Copy after login

2,使用:

//打印输出查询结果(假设你的结果)$arr=array();while($list=mssql_fetch_row($row)){	$arr[]=$list;}$s=auto_charset($arr,'gbk','utf-8');//打印试试,在浏览器设置编码为UFT-8,看没有乱码print_r($s);die();
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template