我正在做:
file_put_contents("txt/myfile.txt", $fileContents);
我尝试了很多方法来强制我的文本文件是ANSI,如:
$fileContents = mb_convert_encoding($fileContents , mb_detect_encoding($fileContents , mb_detect_order(), true), 'WINDOWS-1252');
我也尝试过:
$fileContents = iconv("ISO-8859-1", "WINDOWS-1252", $fileContents );
我需要ANSI,因为当我使用MS-DOS中的“type”命令(Windows 7中的cmd.exe)打开它时,文本文件应该看起来不错
如果我打开当前文件,我可以看到UTF-8 BOM:
C:\ Users \ XXX>键入C:\ myfile.txt
´╗┐V017666999 00000000000000005350005122013
如果我用Notepad ++打开文件并应用“转换为ANSI”,我得到(我需要的):
C:\ Users \ XXX>键入C:\ myfile.txt
V017666999 00000000000000535350005122013
有什么办法可以解决这个问题吗?提前致谢。
如果PHP文件中包含非ASCII字符,则需要首先转换PHP文件的编码。
如果您的非ASCII字符来自某些外部源,则需要对其进行iconv。但不是来自ISO-8859-1,而是来自外部源的编码。
现在我知道发生了什么,文件正确创建,但下载时会添加不需要的BOM。
这是问题,我只需要改变这个:
/* Bad code */
header('Content-disposition: attachment; filename='.$_GET['filename']);
header('Content-type: application/txt');
readfile($_GET['filename']);
对此(下载为二进制文件,使其保持不变):
/* Good code */
header('Content-disposition: attachment; filename='.$_GET['filename']);
header('Content-type: application/txt');
header('Content-Transfer-Encoding: binary');
header('Content-Description: File Transfer');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
ob_clean();
flush();
readfile('txt/'.$_GET['filename']);
(这最初是作为问题的编辑发布的,但@Daniel建议发布澄清的答案)。