Convert();}function SetGb2312($InStr="gb2312.txt"){ // 设置gb2312代码文">
当前位置:Gxlcms > PHP教程 > php进行GB2312与UTF8编码转换的代码

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

时间:2021-07-01 10:21:17 帮助过:34人阅读

  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 < 0x80) {
  54. $str.=ord($InStr);
  55. }
  56. else if ($InStr < 0x800) {
  57. $str.=(0xC0 | $InStr>>6);
  58. $str.=(0x80 | $InStr & 0x3F);
  59. }
  60. else if ($InStr < 0x10000) {
  61. $str.=(0xE0 | $InStr>>12);
  62. $str.=(0x80 | $InStr>>6 & 0x3F);
  63. $str.=(0x80 | $InStr & 0x3F);
  64. }
  65. else if ($InStr < 0x200000) {
  66. $str.=(0xF0 | $InStr>>18);
  67. $str.=(0x80 | $InStr>>12 & 0x3F);
  68. $str.=(0x80 | $InStr>>6 & 0x3F);
  69. $str.=(0x80 | $InStr & 0x3F);
  70. }
  71. return $str;
  72. }
  73. }
  74. ?>

测试下,看看效果:

  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)输出英文。

人气教程排行