问题描述:

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!

网友答案:

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);
 }
}
相关阅读:
Top