search
Homephp教程php手册PHP对GB编码动态转UTF-8几种方法评测
PHP对GB编码动态转UTF-8几种方法评测Jun 13, 2016 am 10:29 AM
phputf-8oneseveral kindsdynamicexistrightmentionedmethodusecodingReviewchange

在《IP地址->地理位置转换的测评》一文中提到用ip2addr函数直接读取IP数据库文件是效率最高的,相比用MySQL数据库存储IP数据,用SQL查询是效率最低的。但是IP数据库文件QQWry.dat是GB2312编码的。现在我需要UTF-8编码的地理位置结果。如果用MySQL方法,可以在数据存入数据库时就转换为UTF-8编码,一劳永逸。但是QQWry.dat文件又无法修改,只能把ip2addr函数的输出结果再进行动态转换。

动态转换GB->UTF-8编码至少有四种方法:

用PHP的iconv扩展转换

用PHP的mb_string扩展转换

用对换表转换,对换表存储在MySQL数据库中

用对换表转换,对换表存储在文本文件中

前两种方法要服务器作了相应设置(编译安装了相应扩展)才能使用。我的虚拟主机没有这两个扩展,只好考虑后两种方法。前两个方法本文也不进行测评。

测评程序如下(func_ip.php参见《IP地址->地理位置转换的测评》一文):

require_once ("func_ip.php");
function u2utf8($c) {
 $str = "";
 if ($c    $str .= $c;
 } elseif ($c    $str .= chr(0xC0 | $c >> 6);
   $str .= chr(0x80 | $c & 0x3F);
 } elseif ($c    $str .= chr(0xE0 | $c >> 12);
   $str .= chr(0x80 | $c >> 6 & 0x3F);
   $str .= chr(0x80 | $c & 0x3F);
 } elseif ($c    $str .= chr(0xF0 | $c >> 18);
   $str .= chr(0x80 | $c >> 12 & 0x3F);
   $str .= chr(0x80 | $c >> 6 & 0x3F);
   $str .= chr(0x80 | $c & 0x3F);
 }
 return $str;
}
function GB2UTF8_SQL($strGB) {
 if (!trim($strGB)) return $strGB;
 $strRet = "";
 $intLen = strlen($strGB);
 for ($i = 0; $i    if (ord($strGB{$i}) > 127) {
       $strCurr = substr($strGB, $i, 2);
       $intGB = hexdec(bin2hex($strCurr)) - 0x8080;
       $strSql = "SELECT code_unicode FROM nnstats_gb_unicode
         WHERE code_gb = ".$intGB." LIMIT 1"
       ;
       $resResult = mysql_query($strSql);
       if ($arrCode = mysql_fetch_array($resResult)) $strRet .= u2utf8($arrCode["code_unicode"]);
       else $strRet .= "??";
       $i++;
   } else {
       $strRet .= $strGB{$i};
   }
 }
 return $strRet;
}
function GB2UTF8_FILE($strGB) {
 if (!trim($strGB)) return $strGB;
 $arrLines = file("gb_unicode.txt");
 foreach ($arrLines as $strLine) {
   $arrCodeTable[hexdec(substr($strLine, 0, 6))] = hexdec(substr($strLine, 7, 6));
 }
 $strRet = "";
 $intLen = strlen($strGB);
 for ($i = 0; $i    if (ord($strGB{$i}) > 127) {
       $strCurr = substr($strGB, $i, 2);
       $intGB = hexdec(bin2hex($strCurr)) - 0x8080;
       if ($arrCodeTable[$intGB]) $strRet .= u2utf8($arrCodeTable[$intGB]);
       else $strRet .= "??";
       $i++;
   } else {
       $strRet .= $strGB{$i};
   }
 }
 return $strRet;
}
function EncodeIp($strDotquadIp) {
 $arrIpSep = explode(., $strDotquadIp);
 if (count($arrIpSep) != 4) return 0;
 $intIp = 0;  
 foreach ($arrIpSep as $k => $v) $intIp += (int)$v * pow(256, 3 - $k);
 return $intIp;
 //return sprintf(\%02x%02x%02x%02x, $arrIpSep[0], $arrIpSep[1], $arrIpSep[2], $arrIpSep[3]);
}
function GetMicroTime() {
 list($msec, $sec) = explode(" ", microtime());
 return ((double)$msec + (double)$sec);
}
for ($i = 0; $i  $strIp = mt_rand(0, 255).".".mt_rand(0, 255).".".mt_rand(0, 255).".".mt_rand(0, 255);
 $arrAddr[$i] = ip2addr(EncodeIp($strIp));
}
$resConn = mysql_connect("localhost", "netnest", "netnest");
mysql_select_db("test");
// 测评MySQL查询的编码转换
$dblTimeStart = GetMicroTime();
for ($i = 0; $i  $strUTF8Region = GB2UTF8_SQL($arrAddr[$i]["region"]);
 $strUTF8Address = GB2UTF8_SQL($arrAddr[$i]["address"]);
}
$dblTimeDuration = GetMicroTime() - $dblTimeStart;
// 测评结束并输出结果
echo $dblTimeDuration; echo " ";
// 测评文本文件查询的编码转换
$dblTimeStart = GetMicroTime();
for ($i = 0; $i  $strUTF8Region = GB2UTF8_FILE($arrAddr[$i]["region"]);
 $strUTF8Address = GB2UTF8_FILE($arrAddr[$i]["address"]);
}
$dblTimeDuration = GetMicroTime() - $dblTimeStart;
// 测评结束并输出结果
echo $dblTimeDuration; echo " ";
?>


测评两次结果(精确到3位小数,单位是秒):

MySQL查询转换:0.112
文本查询转换:10.590

MySQL查询转换:0.099
文本查询转换:10.623

可见这次是MySQL方法遥遥领先于文件查询法。但是现在还不急于使用MySQL方法,因为文本文件方法之所以如此耗时,主要因为它每次转换都要把整个gb_unicode.txt读入内存,而gb_unicode.txt又是文本文件,格式如下:

0x2121   0x3000   # IDEOGRAPHIC SPACE
0x2122   0x3001   # IDEOGRAPHIC COMMA
0x2123   0x3002   # IDEOGRAPHIC FULL STOP
0x2124   0x30FB   # KATAKANA MIDDLE DOT
0x2125   0x02C9   # MODIFIER LETTER MACRON (Mandarin Chinese first tone)
……
0x552A   0x6458   #
0x552B   0x658B   #
0x552C   0x5B85   #
0x552D   0x7A84   #
……
0x777B   0x9F37   #
0x777C   0x9F3D   #
0x777D   0x9F3E   #
0x777E   0x9F44   #


文本文件效率较低,于是考虑把文本文件转换为二进制文件,然后用折半法查找这个文件,而不需要把整个文件读入内存。文件格式为:文件头2字节,存储记录数;接着一条接一条记录存入文件,每条记录4字节,前2字节对应GB代码,后2字节对应Unicode代码。转换程序如下:

$arrLines = file("gb_unicode.txt");
foreach ($arrLines as $strLine) {
 $arrCodeTable[hexdec(substr($strLine, 0, 6))] = hexdec(substr($strLine, 7, 6));
}
ksort($arrCodeTable);
$intCount = count($arrCodeTable);
$strCount = chr($intCount % 256) . chr(floor($intCount / 256));
$fileGBU = fopen("gbu.dat", "wb");
fwrite($fileGBU, $strCount);
foreach ($arrCodeTable as $k => $v) {
 $strData = chr($k % 256) . chr(floor($k / 256)) . chr($v % 256) . chr(floor($v / 256));
 fwrite($fileGBU, $strData);
}
fclose($fileGBU);
?>

执行程序后就获得了二进制的GB->Unicode对照表gbu.dat,并且数据记录按GB代码排了序,便于折半法查找。使用gbu.dat进行转码的函数如下:

function GB2UTF8_FILE1($strGB) {
 if (!trim($strGB)) return $strGB;
 $fileGBU = fopen("gbu.dat", "rb");
 $strBuf = fread($fileGBU, 2);
 $intCount = ord($strBuf{0}) + 256 * ord($strBuf{1});
 $strRet = "";
 $intLen = strlen($strGB);
 for ($i = 0; $i    if (ord($strGB{$i}) > 127) {
       $strCurr = substr($strGB, $i, 2);
       $intGB = hexdec(bin2hex($strCurr)) - 0x8080;
       $intStart = 1;
       $intEnd = $intCount;
       while ($intStart          $intMid = floor(($intStart + $intEnd
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version