PHP / Output file Encoding / Changing from ANSI to UTF-8-BOM

186 Views Asked by At

Is there a way to prevent PHP to auto-changing encoding for Excel-file or set encoding?

Already tried:

ini_set('default_charset', 'ANSI');
ini_set('output_encoding', 'ANSI');
header('Content-Type: application/vnd.ms-excel; charset=ANSI');

Using "phpoffice/phpexcel". If I save built Excel-file on server, and download saved file without PHP, than encoding for that file in NotePad++ is ANSI, and file opens correctly in MS Excel program.

But if I tried to return that correct file by PHP:

readfile($file_path);
// OR directly write to output
$objWriter->save('php://output');

Then downloaded Excel-file encoding will be UTF-8-BOM, end MS Excel shows for that file only strange symbols. But I can open that file in NotePad++ and change encoding to ANSI, then that file correctly opens in MS Excel.

How to return with PHP that Excel-file to client without auto-changing encoding of that file?

1

There are 1 best solutions below

0
EarthLing On

Thanks to @CBroe and Detecting UTF BOM (byte order mark) using PHP, before set "attachment" headers putted that:

$has_bomed_files = false;
foreach (get_included_files() as $file_path)
{
    $str = file_get_contents($file_path);
    $bom = pack("CCC", 0xef, 0xbb, 0xbf);
    if (0 === strncmp($str, $bom, 3))
    {
        $has_bomed_files = true;
        print $file_path;
        print '<br>';
    }
}

if ($has_bomed_files)
    exit(__FILE__ . ":" . __LINE__);

And found, was BOM in one Class, I`ve removed that BOM, and now PHP returns correct Excel-file.