2010年2月5日 星期五

[php Utf-8 轉 Big5]

來源網站
因為utf8 的字集大過於big5

Header("Expires: Mon , 26Jul 1997 05 : 00 : 00 GMT");
Header("Last-Modified: ".gmdate("D,dMYH:i:s")."GMT");
Header("Content-Type: text/html; charset=big5");

function ecstart_gbk_convert($buffer){
$slen=strlen($buffer);
$buffero=$buffer;
$buffer=iconv("gbk","big5",$buffer);
$olen=strlen($buffer);
if($slen != $olen)
{
$buffer=$buffer.ecstart_gbk2htmlunicode(substr($buffero,$olen,2)).ecstart_gbk_convert(substr($buffero,$olen+2));
}
return $buffer;
}

function ecstart_gbk2htmlunicode($buffer){
$len=strlen($buffer);
for($i=0;$i<$len;$i++)
{
$h=ord($buffer[$i]);
if($h >= 0x81){
$tmpstr=iconv("gbk","utf-16",$buffer[$i].$buffer[$i+1]);
$uni=hexdec(bin2hex($tmpstr[3].$tmpstr[2]));
$unicode .= "&#".$uni.";";
$i++;
}else{
$unicode .= $string[$i];
}
}
return $unicode;
}
function ecstart_utf8_convert($buffer){
$buffer=iconv("utf-8","gbk",$buffer);
$buffer=ecstart_gbk_convert($buffer);
return $buffer;
}


$filename = "ch_code.txt";
$handle = fopen($filename, "r");
$str = fread($handle, filesize($filename));
fclose($handle);
echo "<pre>";

echo "會斷掉的寫法 : ";
echo "\n";
echo iconv('UTF-8','BIG5',$str);

echo "\n";
echo "\n";
echo "\n";
echo "修正後的寫法 : ";
echo "\n";
echo ecstart_utf8_convert($str);

【下列文章您可能也有興趣】

沒有留言: