如何为 PHP 文件设置 UTF-8 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5056646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set UTF-8 encoding for a PHP file
提问by Tomasz Smykowski
I have a PHP script called :
我有一个名为的 PHP 脚本:
http://cyber-flick.com/apiMorpho.php?method=getMorphoData&word=kot
http://cyber-flick.com/apiMorpho.php?method=getMorphoData&word=kot
That displays some data in plain text:
以纯文本形式显示一些数据:
Cz?????? mowy: rzeczownik
Przypadek: dope??niacz
Rodzaj: ??e??ski
Liczba: mnoga
As you can see in place of proper chars there are so "bushes". What i would like to do is display this in a way so that people see in browser proper UTF-8 characters.
正如你所看到的,在适当的字符的地方有很多“灌木丛”。我想要做的是以一种方式显示它,以便人们在浏览器中看到正确的 UTF-8 字符。
You can encapsulate it in HMTL tags and set in meta UTF-8 encoding, but because the data received from this script will be processed further I don't want to use any HTML tags, it should be only plain text result set.
您可以将其封装在 HMTL 标签中并设置为元 UTF-8 编码,但因为从该脚本接收的数据将被进一步处理,我不想使用任何 HTML 标签,它应该只是纯文本结果集。
So is there a way to inform browser that this file is UTF-8 without using meta tags?
那么有没有办法在不使用元标记的情况下通知浏览器这个文件是UTF-8?
PS. File is encoded in UTF-8 and if I manually change charset encoding in my browser to UTF-8 it displays ok, but what I want to acomplish is people to not be required to do so.
附注。文件以 UTF-8 编码,如果我手动将浏览器中的字符集编码更改为 UTF-8,它显示正常,但我想要完成的是人们不需要这样做。
回答by delphist
header('Content-type: text/plain; charset=utf-8');
回答by Larry Judd
Also note that setting a header to "text/plain"
will result in all html and php (in part) printing the characters on the screen as TEXT, not as HTML. So be aware of possible HTML not parsing when using text type plain
.
另请注意,将标题设置为"text/plain"
将导致所有 html 和 php(部分)将屏幕上的字符打印为 TEXT,而不是 HTML。因此,请注意在使用 text type 时可能无法解析 HTML plain
。
Using:
使用:
header('Content-type: text/html; charset=utf-8');
Can return HTML and PHP as well. Not just text.
也可以返回 HTML 和 PHP。不仅仅是文字。
回答by Jan Dragsbaek
PHP, by default, always returns the following header: "Content-Type: text/html" (notice no charset), therefore you must use
默认情况下,PHP 始终返回以下标题:“Content-Type: text/html”(注意没有字符集),因此您必须使用
<?php header('Content-type: text/plain; charset=utf-8'); ?>
回答by Intrepidd
Try this way header('Content-Type: text/plain; charset=utf-8');
试试这个方法 header('Content-Type: text/plain; charset=utf-8');
回答by zerkms
You have to specify what encoding the data is. Either in meta or in headers
您必须指定数据的编码方式。无论是在元数据中还是在标题中
header('Content-Type: text/plain; charset=utf-8');
回答by Patrick-Peng
HTML file:
HTML文件:
<head>
<meta charset="utf-8">
</head>
PHP file :
PHP文件:
<?php header('Content-type: text/plain; charset=utf-8'); ?>