If the use of Iconv () function conversion code is relatively simple, but many virtual host does not support this component, I find a half-day on the Internet, only to find a gb2312 to Utf-8 method, but not reverse conversion.
This function is as follows:
/*******************************
GB Rotary UTF-8 encoding
*******************************/
function Gb2utf8 ($GBSTR) {
Global $CODETABLE;
if (Trim ($gbstr) = = "") return $gbstr;
if (empty ($CODETABLE)) {
$filename = DirName (__file__). " /gb2312-utf8.table ";
$fp = fopen ($filename, "R");
while ($l = fgets ($fp, 15))
{$CODETABLE [Hexdec (substr ($l, 0, 6)] = substr ($l, 7, 6);}
Fclose ($FP);
}
$ret = "";
$utf 8 = "";
while ($GBSTR) {
if (Ord (substr ($gbstr, 0, 1)) > 127) {
$thisW = substr ($gbstr, 0, 2);
$gbstr = substr ($gbstr, 2, strlen ($GBSTR));
$utf 8 = "";
@ $utf 8 = U2utf8 (Hexdec ($CODETABLE [Hexdec (Bin2Hex ($thisW))-0x8080]);
if ($utf 8!= "") {
for ($i = 0; $i < strlen ($utf 8); $i = 3)
$ret. = Chr (substr ($utf 8, $i, 3));
}
}
Else
{
$ret. = substr ($gbstr, 0, 1);
$gbstr = substr ($gbstr, 1, strlen ($GBSTR));
}
}
return $ret;
}
Unicode Turn UTF8
function U2utf8 ($c) {
for ($i = 0; $i < count ($c); $i)
$str = "";
if ($c < 0x80) {
$str. = $c;
else if ($c < 0x800) {
$str. = (0xc0 | $c >> 6);
$str. = (0x80 | $c & 0x3F);
else if ($c < 0x10000) {
$str. = (0xe0 | $c >> 12);
$str. = (0x80 | $c >> 6 & 0x3F);
$str. = (0x80 | $c & 0x3F);
else if ($c < 0x200000) {
$str. = (0xF0 | $c >> 18);
$str. = (0x80 | $c >> & 0x3F);
$str. = (0x80 | $c >> 6 & 0x3F);
$str. = (0x80 | $c & 0x3F);
}