php进行GB2312与UTF8编码转换的代码

原创
2016-07-25 09:08:07 690浏览
  1. Class GB2UTF8

  2. {
  3. var $gb; // 待转换的GB2312字符串
  4. var $utf8; // 转换后的UTF8字符串
  5. var $CodeTable; // 转换过程中使用的GB2312代码文件数组
  6. var $ErrorMsg; // 转换过程之中的错误讯息
  7. function GB2UTF8($InStr="")

  8. {
  9. $this->gb=$InStr;
  10. $this->SetGb2312();
  11. ($this->gb=="")?0:$this->Convert();
  12. }
  13. function SetGb2312($InStr="gb2312.txt")

  14. { // 设置gb2312代码文件,默认为gb2312.txt
  15. $this->ErrorMsg="";
  16. $tmp=@file($InStr);
  17. if (!$tmp) {
  18. $this->ErrorMsg="No GB2312";
  19. return false;
  20. }
  21. $this->CodeTable=array();
  22. while(list($key,$value)=each($tmp)) {
  23. $this->CodeTable[hexdec(substr($value,0,6))]=substr($value,7,6);
  24. }
  25. }
  26. function Convert()

  27. { // 转换GB2312字符串到UTF8字符串,需预先设置$gb
  28. $this->utf8="";
  29. if(!trim($this->gb) || $this->ErrorMsg!="") {
  30. return ($this->utf8=$this->ErrorMsg);
  31. }
  32. $str=$this->gb;
  33. while($str) {

  34. if (ord(substr($str,0,1))>127)
  35. {
  36. $tmp=substr($str,0,2);
  37. $str=substr($str,2,strlen($str));
  38. $tmp=$this->U2UTF8(hexdec($this->CodeTable[hexdec(bin2hex($tmp))-0x8080]));
  39. for($i=0;$i$this->utf8.=chr(substr($tmp,$i,3));
  40. }
  41. else
  42. {
  43. $tmp=substr($str,0,1);
  44. $str=substr($str,1,strlen($str));
  45. $this->utf8.=$tmp;
  46. }
  47. }
  48. return $this->utf8;
  49. }
  50. function U2UTF8($InStr)

  51. {
  52. for($i=0;$i$str="";
  53. if ($InStr $str.=ord($InStr);
  54. }
  55. else if ($InStr $str.=(0xC0 | $InStr>>6);
  56. $str.=(0x80 | $InStr & 0x3F);
  57. }
  58. else if ($InStr $str.=(0xE0 | $InStr>>12);
  59. $str.=(0x80 | $InStr>>6 & 0x3F);
  60. $str.=(0x80 | $InStr & 0x3F);
  61. }
  62. else if ($InStr $str.=(0xF0 | $InStr>>18);
  63. $str.=(0x80 | $InStr>>12 & 0x3F);
  64. $str.=(0x80 | $InStr>>6 & 0x3F);
  65. $str.=(0x80 | $InStr & 0x3F);
  66. }
  67. return $str;
  68. }
  69. }
  70. ?>
复制代码

测试下,看看效果:

  1. Header("Content-type: image/png");
  2. $im = imagecreate(400,300);
  3. $black = ImageColorAllocate($im, 0,0,0);
  4. $white = ImageColorAllocate($im, 184,44,6);
  5. include("gb2utf8.php");
  6. $obj=new gb2utf8();
  7. $obj->gb="123abc中国456def测试正确";
  8. $obj->Convert();
  9. ImageTTFText($im, 20, 0, 5, 50, $white, "SIMKAI.TTF", $obj->utf8);
  10. ImagePNG($im);
  11. ImageDestroy($im);
  12. ?>
复制代码

注解: 需要正确设置font文件,请先确认是否能够使用font直接(不使用gb2utf8)输出英文。



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。