经测试代码如下:
/**
* UTF-8完美转换GB2312(GBK)
*
* @param
* @author 编程之家 jb51.cc jb51.cc
**/
function GetGB2312String($name) {
$tostr = "";
for($i=0;$i<strlen($name);$i++) {
$curbin = ord(substr($name,$i,1));
if($curbin < 0x80) {
$tostr .= substr($name,1);
} elseif($curbin < bindec("11000000")) {
$str = substr($name,1);
$tostr .= "&#".ord($str).";";
} elseif($curbin < bindec("11100000")) {
$str = substr($name,2);
$tostr .= "&#".GetUnicodeChar($str).";";
$i += 1;
} elseif($curbin < bindec("11110000")) {
$str = substr($name,3);
$gstr= iconv("UTF-8","GB2312",$str);
if(!$gstr) {
$tostr .= "&#".GetUnicodeChar($str).";";
} else {
$tostr .= $gstr;
}
$i += 2;
} elseif($curbin < bindec("11111000")) {
$str = substr($name,4);
$tostr .= "&#".GetUnicodeChar($str).";";
$i += 3;
} elseif($curbin < bindec("11111100")) {
$str = substr($name,5);
$tostr .= "&#".GetUnicodeChar($str).";";
$i += 4;
} else {
$str = substr($name,6);
$tostr .= "&#".GetUnicodeChar($str).";";
$i += 5;
}
}
return $tostr;
}
function GetUnicodeChar($str) {
$temp = "";
for($i=0;$i<strlen($str);$i++) {
$x = decbin(ord(substr($str,1)));
if($i == 0) {
$s = strlen($str)+1;
$temp .= substr($x,$s,8-$s);
} else {
$temp .= substr($x,2,6);
}
}
return bindec($temp);
}
//程序使用:
$value = GetGB2312String($value);