Sending a CSV file

18. 12. 2022

When sending binary files, always think about what HTTP headers to choose. In case of sending a CSV file (almost ideal format for simple text tables, which can be processed by Excel), Content-Type: application/csv, in UTF-8 encoding is useful.

However, in some versions of Excel there is a problem with UTF-8 encoding. To make sure that the correct encoding is detected, we need to insert the UTF-8 BOM, which is a special character xEF\xBB\xBF that tells the client that it is UTF-8, since it does not exist in any other encoding.

Therefore, send the headers as follows:

php
header('Content-Type: application/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=' . date('d-m-y') . '_file.csv');
header('Pragma: no-cache');
echo "\xEF\xBB\xBF";
Jan Barášek
Jan BarášekVíce o autorovi

Autor článku pracuje jako seniorní vývojář a software architekt v Praze. Navrhuje a spravuje velké webové aplikace, které znáte a používáte. Od roku 2009 nabral bohaté zkušenosti, které tímto webem předává dál.

Rád vám pomůžu:

Newsletter

Nejlepsi tipy a triky o PHP do Vaseho e-mailu. Clanky a novinky nejen ze sveta PHP a programovani.