如何在PHP中设置文本文件编码? [英] How to set text file encoding in PHP?
问题描述
如何在PHP中设置文本文件ENCODING(例如UTF-8)?
让我告诉你我的问题。这是我的代码:
<?php
file_put_contents('test.txt',$ data); //数据是一些带有UTF-8字符集的非英语文本
?>
输出:اÙ
!
fwrite()
有类似的输出。
当我通过记事本创建 test.txt
并设置字符集 UTF-8 的输出是我想要的。
我想在PHP文件中设置字符集。
现在这是我的问题:如何通过PHP设置文本文件编码?
PHP在文件中存储文本时不应用编码:它存储的数据完全按照字符串中的布局。
您提到在 notepad.exe
中打开文件时出现问题。该文本编辑器不是很擅长猜测你打开的文件的编码;如果文本以UTF-8编码,则必须选择将其打开为UTF-8。如果可能,请使用其他文本编辑器。 记事本++ 是常见的替代品。
如果必须使用 notepad.exe
,作为最后手段,请写一个字节顺序标记该文件在你写任何东西之前;这将使它将文件识别为UTF-8,同时可能使文件无法用于其他目的(有关详细信息,请参阅维基百科文章)。
file_put_contents(file.txt,\xEF\xBB\xBF。$ data);
How can I set a text file ENCODING (for instance UTF-8) in PHP?
Let me show you my problem. This is my code:
<?php
file_put_contents('test.txt', $data); // data is some non-English text with UTF-8 charset
?>
Output: اÙ
!
fwrite()
has the similar output.
But when I create the test.txt
by notepad and set the charset UTF-8 the output is what I want.
I wanna set the charset in the PHP file.
Now this is my question: How to set text file encoding by PHP?
PHP does not apply an encoding when storing text in a file: it stores data exactly as it is laid out in the string.
You mention that you have problems opening the file in notepad.exe
. That text editor is not very good at guessing the encoding of the file you are opening; if the text is encoded in UTF-8 you must choose to open it as UTF-8. Use another text editor if possible. Notepad++ is a popular replacement.
If you must use notepad.exe
, as a last resort, write a Byte Order Mark to the file before you write anything else; this will make it recognize the file as UTF-8 while potentially making the file unusable for other purposes (see the Wikipedia article for details).
file_put_contents("file.txt", "\xEF\xBB\xBF" . $data);
这篇关于如何在PHP中设置文本文件编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!