Search code examples
phputf-8ansiplaintext

PHP - How to save text file with ANSI encoding?


I'm doing:

file_put_contents("txt/myfile.txt", $fileContents);

I have tried many ways to force my text file to be ANSI, like:

$fileContents = mb_convert_encoding($fileContents , mb_detect_encoding($fileContents , mb_detect_order(), true), 'WINDOWS-1252');

I have also tried:

$fileContents = iconv("ISO-8859-1", "WINDOWS-1252", $fileContents );

I need ANSI because the text file should look nice when I open it with the "type" command from MS-DOS (cmd.exe in Windows 7)

If I open my current file I can see the UTF-8 BOM:

C:\Users\XXX>type C:\myfile.txt

´╗┐V017666999 00000000000000005350005122013

If I open the file with Notepad++ and apply "Convert to ANSI" I get (what I need):

C:\Users\XXX>type C:\myfile.txt

V017666999 00000000000000005350005122013

Is there any way I can fix this? Thanks in advance.


Solution

  • Now I know what happened, the file is being created correctly, but the undesired BOM is added when I download it.

    This is the problem, I just had to change this:

    /* Bad code */
    header('Content-disposition: attachment; filename='.$_GET['filename']);
    header('Content-type: application/txt');
    readfile($_GET['filename']);
    

    to this (Download as binary file so it remains intact):

    /* 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']);
    

    (This was originally posted as an edit on the question, but @Daniel suggested posting an answer for clarification).