页面乱码问题的根源及其分析
这个问题已经遇到过俩次了,就是页面中明确指明了编码是
UTF8,但是显示是乱码。虽然知
道解决方法,也知道是
Apache 的原因,但是一直没有去找其所以然,今天趁机,一览 PHP
工程师就研究了一下
首先
, 关闭 PHP 配置文件 php.ini 中的 default_charset:
1. 页面没有指定 charset , Apache 配置 defaultcharst gbk , 页面文件编码是 utf-8
结果
: 乱码,使用 wireshark 抓包,发现服务器返回的 header 中指明了:
代码如下
:
Content-Type:text/html;charset=GB
结论:当页面没有指明
charset 的时候,Apache 的 defaultcharset 起作用
2. 页面指定 charset 为 utf-8, Apache 配置 defaultcharset gbk. 页面文件是 utf-8
代码如下
:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="page-header">
测试
Apache DefaultCharset
</div>
</body>
</html>
结果还是出现乱码。
结论:当
Apache 配置了 DefaultCharset, 将忽略页面的 charset 申明。
3. PHP header 申明 charset 为 utf8, Apache 配置 defaultcharst gbk,页面文件编码是 utf8
代码如下
:
header("Content-Type:text/html; charset=utf-8");
结果
: 页面显示正常。
4 Apache 设置 DefaultCharset off
结果,页面显示正常。
翻阅了下
Apache2 的手册:
AddDefaultCharset 指令
说明当应答内容是
text/plain 或 text/html 时,在 HTTP 应答头中加入的默认字符集
语法
AddDefaultCharsetOn|Off|charset
默认值
AddDefaultCharsetOff