找回密码
 立即注册

QQ登录

只需一步,快速开始

查看: 1189|回复: 0
打印 上一主题 下一主题

用PHP实现将GB编码转换为UTF8

[复制链接]

2500

主题

2513

帖子

7520

积分

论坛元老

Rank: 8Rank: 8

积分
7520
跳转到指定楼层
楼主
发表于 2018-2-14 09:40:32 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

            gb2utf8.php 文件如下:
[U]复制代码[/U] 代码如下:
gb=$InStr;  
$this->SetGb2312();  
($this->gb=="")?0this->Convert();  
}  
function SetGb2312($InStr="gb2312.txt")  
{ // 设置gb2312代码文件,默认为gb2312.txt  
$this->ErrorMsg="";  
$tmp=@file($InStr);  
if (!$tmp) {  
$this->ErrorMsg="No GB2312";  
return false;  
}  
$this->CodeTable=array();  
while(list($key,$value)=each($tmp)) {  
$this->CodeTable[hexdec(substr($value,0,6))]=substr($value,7,6);  
}  
}  
function Convert()  
{ // 转换GB2312字符串到UTF8字符串,需预先设置$gb  
$this->utf8="";  
if(!trim($this->gb) || $this->ErrorMsg!="") {  
return ($this->utf8=$this->ErrorMsg);  
}  
$str=$this->gb;  
while($str) {  
if (ord(substr($str,0,1))>127)  
{  
$tmp=substr($str,0,2);  
$str=substr($str,2,strlen($str));  
$tmp=$this->U2UTF8(hexdec($this->CodeTable[hexdec(bin2hex($tmp))-0x8080]));  
for($i=0;$iutf8.=chr(substr($tmp,$i,3));  
}  
else  
{  
$tmp=substr($str,0,1);  
$str=substr($str,1,strlen($str));  
$this->utf8.=$tmp;  
}  
}  
return $this->utf8;  
}  
function U2UTF8($InStr)  
{  
for($i=0;$i>6);  
$str.=(0x80 | $InStr & 0x3F);  
}  
else if ($InStr >12);  
$str.=(0x80 | $InStr>>6 & 0x3F);  
$str.=(0x80 | $InStr & 0x3F);  
}  
else if ($InStr >18);  
$str.=(0x80 | $InStr>>12 & 0x3F);  
$str.=(0x80 | $InStr>>6 & 0x3F);  
$str.=(0x80 | $InStr & 0x3F);  
}  
return $str;  
}  
}
?>
测试文件如下:
[U]复制代码[/U] 代码如下:
gb="123abc中国456def测试正确";  
$obj->Convert();  
ImageTTFText($im, 20, 0, 5, 50, $white, "SIMKAI.TTF", $obj->utf8);  
ImagePNG($im);  
ImageDestroy($im);
?>

说明:  
需要正确设置font文件,请先确认可以使用font直接(不使用gb2utf8)输出英文。
            
            
您可能感兴趣的文章:
  • php utf-8转unicode的函数
  • PHP UTF8编码内的繁简转换类
  • PHP通过iconv将字符串从GBK转换为UTF8字符集
  • PHP函数篇详解十进制、二进制、八进制和十六进制转换函数说明
  • PHP中实现中文字符进制转换原理分析
  • 支持生僻字且自动识别utf-8编码的php汉字转拼音类
  • PHP如何实现Unicode和Utf-8编码相互转换
  • PHP二进制与字符串之间的相互转换教程
  • 用PHP将Unicode 转化为UTF-8的实现方法(推荐)
  • PHP实现十进制、二进制、八进制和十六进制转换相关函数用法分析
  • PHP实现UTF8二进制及明文字符串的转化功能示例
            
  • 分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
    收藏收藏
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    用户反馈
    客户端