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


转:coolcode.cn
通常情况下,我们的网页要指定一个编码字符集,如 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://phpstudy.net/dxy/nochaoscode/
复制代码 代码如下:

<?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']));
}
?>
<form enctype="multipart/form-data" method="POST">
encode: <input type="text" name="encode" value="UTF-8" /><br />
file: <input type="file" name="file" /><br />
<input type="submit" />
</form>
<form method="POST">
encode: <input type="text" name="encode" value="UTF-8" /><br />
content: <textarea name="content"></textarea><br />
<input type="submit" />
</form>
<form method="POST">
encode: <input type="text" name="encode" value="UTF-8" /><br />
email: <input name="email" /><br />
<input type="submit" />
</form>
<?php
}
?>

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3