php如何转换字符编码为utf8

  • 时间:
  • 来源:网络

   

php转换字符编码为utf8的方法:首先利用mb_detect_encoding()函数找出字符串本身的编码;然后利用mb_convert_encoding()函数进行编码转换即可。

mb_convert_encoding()函数语法:

(推荐教程:php图文教程)

mb_convert_encoding( $str, $encoding1,$encoding2 );

参数:

$str,要转换编码的字符串

$encoding1,目标编码,如utf-8,gbk,大小写均可

$encoding2,原编码,如utf-8,gbk,大小写均可

(视频教程推荐:php视频教程)

思路:

先找出字符串本身的编码,再转换为utf-8编码。

代码实现:

function str_to_utf8 ($str = '') {
    $current_encode = mb_detect_encoding($str, array("ASCII","GB2312","GBK",'BIG5','UTF-8')); 
    $encoded_str = mb_convert_encoding($str, 'UTF-8', $current_encode);
    return $encoded_str;
}