在 PHP 中,当我使用 fwrite 时,我没有得到正确的字符集
这是我的代码:
<?php
header("Content-Type: text/html; charset=UTF-8");
header("Content-Type: application/x-javascript; charset=UTF-8");
$fName = "demo.txt";
$str = "óé";
fid = fopen($fName, 'wb') or die("can't open file"); // Open file
fwrite($fid, $str); // Write to file
fclose($fid); // Close file
?>
在屏幕上,输出为:
óéü
当我打开文件时,我得到:
óéü
我试图使用 fwrite 保存大量数据,但在文件保存时字符编码不正确。
提前致谢。
Here is my code:
<?php
header("Content-Type: text/html; charset=UTF-8");
header("Content-Type: application/x-javascript; charset=UTF-8");
$fName = "demo.txt";
$str = "óé";
fid = fopen($fName, 'wb') or die("can't open file"); // Open file
fwrite($fid, $str); // Write to file
fclose($fid); // Close file
?>
To the screen, the output is:
óéü
When I open the file I get:
óéü
I am trying to save large amounts of data using fwrite, but the characters are not encoding correctly at the point of file save.
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
fwrite
存储二进制字符串。它不进行任何字符集转换。更有可能的是,您的 PHP 脚本的字符集错误,因此原始的
"óéü"
字符串也错误。如果您无法自行调试,请向我们展示bin2hex($str)
和bin2hex(file_get_contents('demo.txt'))
。有一些通用选项可以解决此类问题:
utf8_encode($str)
。fwrite($f, "\xEF\xBB\xBF")
iconv()
正确转换recode L1..UTF8 script.php
fwrite
stores strings binary. It does not do any charset conversion.It's more likely that your PHP script is in a wrong charset, and thus the original
"óéü"
string. Show us thebin2hex($str)
andbin2hex(file_get_contents('demo.txt'))
if you can't debug it yourself.There are some generic options to solve such problems:
utf8_encode($str)
before saving.fwrite($f, "\xEF\xBB\xBF")
iconv()
recode L1..UTF8 script.php
您使用什么程序来“打开”该文件?该程序可能是问题所在。
what program are you using to "open" the file? that program could be the problem.
首先,在 fwrite 中插入 utf_encode,如下所示:
接下来,请记住使用
UTF-8 without BOM
编码保存 PHP 脚本。使用任何高级代码编辑器(例如 Notepad++)来执行此操作。First, insert the utf_encode inside the fwrite, like this:
Next, remember to save your PHP script with
UTF-8 without BOM
encoding. Use any advanced code editor like Notepad++ to do this.