这是我的代码:
<?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保存大量数据,但是文件保存时字符编码不正确。
提前致谢。
答案 0 :(得分:4)
fwrite
存储二进制字符串。它不会进行任何字符集转换。
您的PHP脚本更可能是在错误的字符集中,因此是原始的"óéü"
字符串。如果您无法自行调试,请向我们显示bin2hex($str)
和bin2hex(file_get_contents('demo.txt'))
。
有一些通用选项可以解决这些问题:
utf8_encode($str)
。fwrite($f, "\xEF\xBB\xBF")
iconv()
recode L1..UTF8 script.php
答案 1 :(得分:2)
你用什么程序来“打开”文件?该计划可能是问题所在。
答案 2 :(得分:0)
首先,在fwrite中插入utf_encode,如下所示:
<?php
$fName = "demo.txt";
$str = "óé";
fid = fopen($fName, 'wb') or die("can't open file"); // Open file
fwrite($fid, utf_encode($str)); // Write to file
fclose($fid); // Close file
?>
接下来,请记住使用UTF-8 without BOM
编码保存PHP脚本。使用任何高级代码编辑器(如Notepad ++)来执行此操作。