欢迎光临
我们一直在努力

一段将GB编码转换为utf8的代码-PHP教程,其它文章

建站超值云服务器,限时71元/月

一段将gb编码转换为utf8的代码

gb2utf8.php 文件如下:

class gb2utf8
{
var $gb;          // 待转换的gb2312字符串
var $utf8;        // 转换后的utf8字符串
    var $codetable;   // 转换过程中使用的gb2312代码文件数组
    var $errormsg;    // 转换过程之中的错误讯息

function gb2utf8($instr=””)
{
$this->gb=$instr;
$this->setgb2312();
($this->gb==””)?0:$this->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;$i<strlen ($tmp);$i+=3)
$this->utf8.=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<count($instr);$i++)
$str=””;
if ($instr < 0x80) {
$str.=ord($instr);
}
else if ($instr < 0x800) {
$str.=(0xc0 | $instr>>6);
$str.=(0x80 | $instr & 0x3f);
}
else if ($instr < 0x10000) {
$str.=(0xe0 | $instr>>12);
$str.=(0x80 | $instr>>6 & 0x3f);
$str.=(0x80 | $instr & 0x3f);
}
else if ($instr < 0x200000) {
$str.=(0xf0 | $instr>>18);
$str.=(0x80 | $instr>>12 & 0x3f);
$str.=(0x80 | $instr>>6 & 0x3f);
$str.=(0x80 | $instr & 0x3f);
}
return $str;
}
}

测试文件如下:

php
header(“content-type: image/png”);
$im = imagecreate(400,300);
$black = imagecolorallocate($im, 0,0,0);
$white = imagecolorallocate($im, 184,44,6);
include(“gb2utf8.php”);
$obj=new gb2utf8();
$obj->gb=”123abc中国456def测试正确”;
$obj->convert();
imagettftext($im, 20, 0, 5, 50, $white, “simkai.ttf”, $obj->utf8);
imagepng($im);
imagedestroy($im);

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 一段将GB编码转换为utf8的代码-PHP教程,其它文章
分享到: 更多 (0)