Home > php教程 > PHP源码 > utf8和gb2312编码互转

utf8和gb2312编码互转

PHP中文网
Release: 2016-05-25 17:12:11
Original
1268 people have browsed it

有时遇到编码问题很头疼,从别的网站获取到的中文文本和本站的不同,结果出现乱码,下面的函数可以帮你解决

/********************************************
  *
  * 函数名:get_utf8_to_gb($value)
  * 作  用:utf8编码字符串转换成gb2312编码
  * 作  者:liuqi
  * 日  期:2017-02-09 
  *
  ********************************************/

function   get_utf8_to_gb($value){
  $value_1= $value;
  $value_2   =   @iconv( "utf-8", "gb2312//IGNORE",$value_1);//使用@抵制错误,可能会有一个问题,如果转换字符串中,某一个字符在目标字符集里没有对应字符,那么,这个字符之后的部分就被忽略掉了;也就是说,结果字符串内容不完整。解决办法就是使用//IGNORE 
  $value_3   =   @iconv( "gb2312", "utf-8//IGNORE",$value_2);

 if   (strlen($value_1)   ==   strlen($value_3))
  {
   return   $value_2;
  }else
  {
   return   $value_1;
  }
 }
 /********************************************
  *
  * 函数名:get_gb_to_utf8($value)
  * 作  用:gb2312编码字符串转换成utf8编码
 * 作  者:liuqi
  * 日  期:2017-02-09 
  *
  ********************************************/
 function   get_gb_to_utf8($value){
  $value_1= $value;
  $value_2   =   @iconv( "gb2312", "utf-8//IGNORE",$value_1);
  $value_3   =   @iconv( "utf-8", "gb2312//IGNORE",$value_2);
  if   (strlen($value_1)   ==   strlen($value_3))
  {
   return   $value_2;
  }else
  {
   return   $value_1;
  }
 }
Copy after login

                       


Related labels:
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
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template