HTML文档中未声明字符编码

16

我有一个文件,在它上面出现了一个非常奇怪的错误。这个错误是:

The character encoding of the HTML document was not declared. 
The document will render with garbled text in some browser configurations if 
the document contains characters from outside the US-ASCII range. 
The character encoding of the page must to be declared in the document or 
in the transfer protocol.

这个内容来自文件(indexmws.php):

session_start();
if(!isset($_SESSION['validUser']) || $_SESSION['validUser'] !== true){
header('Location: loginmws.php');
}

include_once('db.php');
include_once('amazonmws.php');
include_once('decidemws.php');
include_once('author.php');
include_once('amazonPricingMWS.php');

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Decision Maker</title>

这是一个完全重复的文件,与不会抛出错误的文件(index.php)完全相同,除了添加了amazonPricingMWS.php并将重定向到标题带有mws.php的页面:

session_start();
if(!isset($_SESSION['validUser']) || $_SESSION['validUser'] !== true){
header('Location: login.php');
}

include_once('db.php');
include_once('amazon.php');
include_once('decide.php');
include_once('author.php');

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Decision Maker</title>

有人能够解释一下为什么我在indexmws.php中会得到这个错误吗?

2个回答

24

出错的原因是浏览器期望在文件的前1024个字节中找到编码格式。这可能是由于第一个文件包含的一些内容被输出了。

现在,浏览器会缓冲文件的前1024个字节以检查字符编码。如果在前1024个字节中未遇到编码描述,则会显示此警告。

在您的情况下,您可以在其他文件被包含之前使用 PHP 标头指定内容类型:

header('Content-type: text/html; charset=utf-8');

了解更多信息,请阅读:http://gtmetrix.com/specify-a-character-set-early.html


10

我有类似的问题,但导致问题的确切原因是我忘记添加以下内容:

<meta content="utf-8" http-equiv="encoding">
在 head 标签中的

后面。
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">

谢谢!这解决了我在Firefox中的错误(我有<script src="/js/t.js" />,但需要HTML添加meta标签)。我在<head>后使用了您的第一个方法(尽管我将其结尾更改为'"/>'以匹配页面上的标签样式)。 - Alexx Roche
@Krishan,你在哪个浏览器上测试过这个? - Pacerier
1
我刚刚尝试了 <meta charset="utf-8"/>,它也起作用了。 - rudolfson

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接