今天准备将IP Search添加到Blog中,结果发现一个问题:纯真数据库使用了gb2312编码,而wordpress用的是utf-8编码。页面显示的是乱码,所以需要找到一个办法在PHP中实现两种编码的互转。
看看PHP Manual,似乎PHP没有像.Net那样专门提供一个Encoding的类,所以只能用其他方法了。网上的方法有两种:
第一种是使用iconv 函数。例如, 下面的例子是利用php将”全”这中编码转换为gb2312.:
[coolcode lang=”php”]
$str = “TTL全天候自动聚焦”;
$str = preg_replace(“|&#([0-9]{1,5});|”, “”.u2utf82gb(\1).””, $str);
$str = “$str=”$str”;”;
eval($str);
echo $str;
function u2utf82gb($c){
$str=””;
if ($c < 0x80) {
$str.=$c;
} else if ($c < 0x800) {
$str.=chr(0xC0 | $c>>6);
$str.=chr(0x80 | $c & 0x3F);
} else if ($c < 0x10000) {
$str.=chr(0xE0 | $c>>12);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
} else if ($c < 0x200000) {
$str.=chr(0xF0 | $c>>18);
$str.=chr(0x80 | $c>>12 & 0x3F);
$str.=chr(0x80 | $c>>6 & 0x3F);
$str.=chr(0x80 | $c & 0x3F);
}
return iconv(‘UTF-8’, ‘GB2312’, $str);
}
?>
[/coolcode]
第二种是使用JavaScript实现的,例如:
[coolcode lang=”javascript”]
string utfinfo = “document.write(“alert(‘aa你好么??’);”);”;
string gb2312info = string.Empty;
Encoding utf8 = Encoding.UTF8;
Encoding gb2312 = Encoding.GetEncoding(“gb2312”);
// Convert the string into a byte[].
byte[] unicodeBytes = utf8.GetBytes(utfinfo);
// Perform the conversion from one encoding to the other.
byte[] asciiBytes = Encoding.Convert(utf8, gb2312, unicodeBytes);
// Convert the new byte[] into a char[] and then into a string.
// This is a slightly different approach to converting to illustrate
// the use of GetCharCount/GetChars.
char[] asciiChars = new char[gb2312.GetCharCount(asciiBytes, 0, asciiBytes.Length)];
gb2312.GetChars(asciiBytes, 0, asciiBytes.Length, asciiChars, 0);
gb2312info = new string(asciiChars);
[/coolcode]
但是上面两种方法的缺点就是太繁了, 其实我们可以使用autogb来完成转化的工作。由于它是对于文件进行操作的,所以我们需要两个临时文件。代码如下:
[coolcode lang=”php”]
$fd=fopen(“/tmp/.marvel01″,”w”);
fwrite($fd, $gbstring);
fclose($fd);
`autogb -i gb -o utf8 /tmp/.marvel02`;
$fd=fopen(“/tmp/.marvel02″,”r”);
echo fgets($fd, 1024);
fclose($fd);
[/coolcode]
这样,我们就能将一个gb2312的字符串转化为utf-8的字符串。这里最需要注意的是程序的安全性,不要给别人任何bug可以利用的。当然 ,你还需要下载autogb这个工具。