I wrote PHP code to export data to .csv file.The exported .csv file was downloadable on my own PC. But in client's server, the .csv file was not downloadable, it was in readable format (the browser can read and print the file contents like a .html file).
Asked
Active
Viewed 135 times
0
-
Possible duplicate of [How to force file download with PHP](https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php) – num8er Jan 11 '18 at 23:35
-
Simply send headers: `header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: Binary'); header('Content-disposition: attachment; filename="report.csv"); ` – num8er Jan 11 '18 at 23:36
-
Still facing that problem only. I was new bee in PHP. I added "header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: Binary'); header('Content-disposition: attachment; filename=report.csv');" this code in server side file. Its shows like raw data but not download csv file. – Jan 12 '18 at 00:02
-
Seems like Your files has issues with UTF8 BOM in file that makes data to be outputted before headers are sent – num8er Jan 12 '18 at 00:03
-
If there is an issue means then why it was working in local server?? – Jan 12 '18 at 00:05
-
Just open Your file in normal PHP editor: VS Code, Sublime, Atom and find UTF8 BOM symbol. Mostly reasons of such anomaly is that evaluated code first outputs bom with text html headers and then comes result of code execution. – num8er Jan 12 '18 at 00:10
-
Oh... Also please add Your code in the question, maybe solution will be simple. – num8er Jan 12 '18 at 00:14
-
$xl_selectQuery = "SELECT * FROM `members` ORDER BY `Mid` ASC"; $connquery = mysqli_query($connection,$xl_selectQuery); while($res = mysqli_fetch_array($connquery)) { echo $res['Member_Name']; } header('Content-Type: application/octet-stream'); header('Content-Transfer-Encoding: Binary'); header('Content-disposition: attachment; filename=report.csv'); – Jan 12 '18 at 00:18
-
Ohhh man... Add that headers before doing echo!))) – num8er Jan 12 '18 at 00:19
-
Thank you so much got output!!! – Jan 12 '18 at 00:24
1 Answers
1
Headers come first:
header('Content-Type: application/octet-stream');
header('Content-Transfer-Encoding: Binary');
header('Content-disposition: attachment; filename=members.csv');
$q = 'SELECT * FROM `members` ORDER BY `Mid` ASC';
$q = mysqli_query($connection, $q);
while ($record = mysqli_fetch_assoc($q)) :
echo $record['Member_Name'];
endwhile;

num8er
- 18,604
- 3
- 43
- 57