PHP - How to save text file with ANSI encoding?

DuckN'Bear picture DuckN'Bear · Dec 4, 2013 · Viewed 12k times · Source

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.

Answer

Vladislav Rastrusny picture Vladislav Rastrusny · Dec 5, 2013

If you have non-ASCII characters in your PHP file, you need to convert encoding of your PHP file in the first place.

If your non-ASCII characters come from some external source, you need to iconv it. But not from ISO-8859-1, but from the encoding of your external source.