您好,欢迎访问一九零五行业门户网

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

网页|显示
通常情况下,我们的网页要指定一个编码字符集,如 gb2312、utf-8、iso-8859-1 等,这样我们就可以在网页上显示我们指定编码的文字了。但是我们很可能会遇到这种情况,那就是我们可能希望在 iso-8859-1 编码的网页上显示汉字,或者在 gb2312 编码的网页上显示韩文等。当然一种解决办法就是我们不用 iso-8859-1 或者 gb2312 编码,而统统都采用 utf-8 编码,这样我们只要在这种编码下,就可以混合显示各国文字了,这是现在很多网站采用的方法。
而我这里所说的并非上面这种方法,因为上面这种方法必须要指定字符集为 utf-8 才可以,一旦用户手工指定为其他字符集,或者可能因为某些原因,那个字符集设置没起作用,而浏览器又没有正确自动识别的话,我们看到的网页还是乱码,尤其是在某些用框架作的网页中,某个框架中的页面如果字符集设置没起作用,在 firefox 中显示乱码而且还没法改变(我是说在不装rightencode插件的情况下)。
而我这里介绍的方法即使是把网页指定为 iso-8859-1 字符集,也能够正确显示汉字、日文等。原理很简单,就是把除了 iso-8859-1 编码中前128个字符以外的所有其他的编码都用 ncr(numeric character reference) 来表示。比如“汉字”这两个字,如果我们写成“汉字”这种形式,那么它在任意字符集下都可以正确显示。根据这个原理,我写了下面这个程序,它可以把现有的网页转化为在任意字符集下都能显示的网页。你只需要指定源网页的字符集和源网页,点提交按钮,就可以得到目标网页了。你也可以只转化某些文字,只需要把文字填写到文本框中,并指定这些文字原来的字符集,点提交按钮,就会在页面上面显示编码后的文字了。另外我还编写了 wordpress 的插件,现在我的 blog 已经可以在任意字符集下都能正确显示了。
转化程序地址:http://test.coolcode.cn/nochaoscode/
下载: nochaoscode.php
?php 
function nochaoscode($encode, $str, $isemail = false) { 
    $str = iconv($encode, utf-16, $str); 
    for ($i = 0; $i  strlen($str); $i++,$i++) { 
        $code = ord($str{$i}) * 256 + ord($str{$i + 1}); 
        if ($code  128 and !$isemail) { 
            $output .= chr($code); 
        } else if ($code != 65279) { 
            $output .= .$code.;; 
        } 
    } 
    return $output; 

$encode = $_post['encode']; 
if ($encode == '') $encode = 'utf-8'; 
if ($_files['file']['size'] > 0) { 
    $data = nochaoscode($encode, file_get_contents($_files['file']['tmp_name'])); 
    header (content-type: application/octet-stream;); 
    header (content-length: .strlen($data)); 
    header (content-disposition: attachment; filename=.$_files['file']['name']); 
    echo $data; 
} else { 
    header (content-type: text/html; charset=utf-8); 
    if ($_post['email']) { 
        echo htmlentities(nochaoscode($encode, $_post['email'], true)); 
    } 
    else { 
        echo htmlentities(nochaoscode($encode, $_post['content'])); 
    } 
?>
encode:
file:
encode:
content:
encode:
email:
?php 

?>
其它类似信息

推荐信息