4
<?php

$filename="backup_".date('m/d/Y', time()).".csv";

header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment;filename="'.$filename.'"');
header('Cache-Control: max-age=0');

$q=mysqli_query($conn,"SELECT * FROM visitordb");
$file = fopen('php://output','w');
if(mysqli_num_rows($q)>0) {
    while($res = $q->fetch_assoc()) {
        $datas = $res["sno"].','.$res["UDID"].','.$res["taggnumber"].','.$res["name"].','.$res["designation"].','.$res["company"].','.$res["email"];
        fputcsv($file, explode(',', $datas));
    }
} else {

}

fclose($file);
}

The above code generates empty line in the beginning of .csv file when viewed in ms excel. One more thing the .csv file also generates any html code in the page.

fullybaked
  • 4,117
  • 1
  • 24
  • 37
warelord
  • 55
  • 1
  • 4
  • Make sure there is no other output from your script, and exit after closing $file – Mark Baker May 17 '13 at 13:57
  • Don't rely on Excel to tell you what a CSV looks like. What does the .csv look like?! – deceze May 17 '13 at 13:58
  • Try to simply save a file to a disk and see if there is an empty line at the beginning. – Viktor S. May 17 '13 at 14:00
  • Also, can you please explain the last statement in your question? That one about HTML – Viktor S. May 17 '13 at 14:03
  • Thank you every one.. Yes I have tried the suggestions still no change.. The csv has an empty line in the beginning.. HTML means the tag etc.. – warelord May 17 '13 at 14:18
  • So, you are saying that you have tried to do `$file = fopen('test.csv','w'); ... ` and that file on server still had an empty line? Have you checked if you do not have an empty line in database? – Viktor S. May 17 '13 at 14:37

1 Answers1

6

what happens if you remove the header directives? You must know that headers are by definition concluded by a new line. I could imagine that this is a \n vs \r\n conflict.

If everything fails, get the whole output into buffer and trim it later:

ob_start();
...your code...
$out = ob_get_contents();
ob_end_clean();
echo trim($out);

Best regards

Zsolt

Zsolt Szilagyi
  • 4,741
  • 4
  • 28
  • 44
  • you're welcome. Beware that trim also removes trailing spaces. Use other string manipulation if you need to keep your csv 100 % safe. – Zsolt Szilagyi May 18 '13 at 17:53
  • @Zsolt Szilagy köszönöm. I had the same problem and didn't know that the header directives were adding a new line. In my case I wrote my output to a temporary file (php's tmpfile()), so I only had to do a ob_end_clean(); before looping through my file and echo'ing it. – BryanT Feb 09 '16 at 15:46