当前位置: 我爱LAMP > PHP > 文章正文

任意字符集下正常显示网页的方法

发表于 2009-12-29 13:33    文章来源:互联网

<?php
// 在任意字符集下正常显示网页的方法
// 测试通过
// 可以在存入数据库前使用

error_reporting(E_ALL);

if(function_exists('mb_convert_encoding')) {// 需要有 Multibyte String 扩展
        $a = mb_convert_encoding('你好', 'HTML-ENTITIES', 'GB2312');
        $b = mb_convert_encoding($a, 'GB2312', 'HTTP-ENTITIES');
        wFile('try.php', $a.'n'.$b);
        /*如果需要对整个页面进行转换,只需要在PHP文件头加上下面三行
        mb_internal_encoding('gb2312');
        mb_http_output('HTML-ENTITIES');
        ob_start('mb_output_handle');
        */
} elseif(function_exists('iconv')) {
        $a = uiconv('gb2312', 'a,世界您好!$%#abc');
        wFile('try.php', $a);
        print $a;
} else print 'sorry my baby';

function wFile($file, $content) {
        $fp = fopen($file, 'w');
        flock($fp, 2);
        fwrite($fp, $content);
        flock($fp, 3);
        fclose($fp);
}

// 使用 iconv 对页面进行转换--测试通过
function uiconv($encode, $string) {
        $string = iconv($encode, 'UTF-16BE', $string);
        $output = '';
        for($i = 0; $i < strlen($string); $i++,$i++) {
                $code = ord($string{$i}) * 256 + ord($string{$i + 1});
                if($code < 128) {
                        $output .= chr($code);// chr 是把英文或是半角符号转换为字符
                } elseif($code != 65279) {
                        $output .= '&#'.$code.';';
                }
        } return $output;
}
?> 

本文链接: http://www.52lamp.com.cn/detail/5896.html

喜欢我爱LAMP – lamp开发程序交流学习平台的文章,那就通过 RSS Feed 功能订阅阅读吧!