0

Im trying to save my sql query as csv using php. Everything goes well except there is a blank row in the beginning of the csv file. How can I remove the blank row at the beginning? Here is my code:

include('connectdb.php');
mysqli_error($mysqli));


header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="online_applicants.csv"');

header('Pragma: no-cache');
header('Expires: 0');

$file = fopen('php://output', 'w');

$sql = "select Firstname from applicant";
$result = mysqli_query($mysqli, $sql) or die("selection error " .      
mysqli_error($mysqli));

while($row = mysqli_fetch_assoc($result))
{
    fputcsv($file, $row);
}



fclose($file);

Thanks!

newbie boy
  • 5
  • 1
  • 5
  • 1
    Stupid question, but are you certain there aren't any blank rows in the database? – Wes H Nov 25 '16 at 01:48
  • I believe that there's no such thing as 'stupid' question mate. ;) Im certain that there's no blank row in my database. And the blank row always occur in the first row of the csv file. – newbie boy Nov 25 '16 at 02:15

1 Answers1

0

Before saving the row, you can try to check if the row is blank, example:

while($row = mysqli_fetch_assoc($result))
{
 if ($row != "") {
    fputcsv($file, $row);
 }
}

Or you can check the size, usually the "blank" row may have something, but the size will be less than a normal row, example:

while($row = mysqli_fetch_assoc($result))
{
 if (strlen($row) > 5) { // if the row has more than 5 characters, put in the file
    fputcsv($file, $row);
 }
}
bruno
  • 151
  • 9
  • There is no blank row in my database but when I open the csv, the result always has a blank row at the beginning. – newbie boy Nov 25 '16 at 02:20
  • Is this blank row, just a linebreak (\n)? – bruno Nov 25 '16 at 02:28
  • but which part of my code puts a linebreak? I tried to echo the result and i didnt see any line breaks. – newbie boy Nov 25 '16 at 02:32
  • Try to remove all line breaks in the script itself, no line breaks between statements, some of these may be affecting the output. – bruno Nov 25 '16 at 02:47
  • Hi! Thank you for all your responses. I solved my problem using the answer [here](http://stackoverflow.com/a/16613766/7202899) – newbie boy Nov 25 '16 at 03:04