Reputation: 4111
I am trying to create a CSV file in my php script. It creates the file but each time it inserts an empty row at the end.
My code is below:
$csv_output .= "Header 0,";
$csv_output .= "Header 1,";
$csv_output .= "Header 2,";
$csv_output .= "Header 3,";
$csv_output .= "Header 4,";
$csv_output .= "\r\n";
// db query...
foreach($rows as $row):
if($row["value_3"] == 10)
{
$x = 'low';
}
else if($row["value_3"] == 100)
{
$x = 'high';
}
$csv_output .= "".$row["value_0"].",";
$csv_output .= "".$row["value_1"].",";
$csv_output .= "".$row["value_2"].",";
$csv_output .= "".$x.",";
$csv_output .= "Constant Always Value Goes here (not in db),";
$csv_output .= "\r\n";
endforeach;
$filename = "csv_".date("d-m-Y_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
print $csv_output;
No matter what my database query is or how many rows the csv contains there is always an empty row at the end. Is there anything causing this?
Upvotes: 1
Views: 2537
Reputation: 6956
You can write the CSV directly to the output like so, and you don't need to format it yourself.
// Send correctly formatted headers
header("Content-type: application/vnd.ms-excel");
// Disposition should be "attachment" followed by optional filename.
header(sprintf('Content-disposition: attachment; filename="csv_%s.csv"', date("d-m-Y_H-i")));
// Open a pointer to the output stream
$fp = fopen('php://output', 'w');
// Build header array
$head = array(
"Header 0",
"Header 1",
"Header 2",
"Header 3"
);
// Write the header array in default csv row format.
fputcsv($fp, $head);
// db query...
// Loop rows
foreach($rows as $row) {
// Write the rows in default csv row format
fputcsv($fp, $row);
}
// Close the output stream
fclose($fp);
An additional benefit is it will use less memory on large downloads, for instance with PDO:
$stmt = $pdo->prepare("SELECT ...");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
This will output each row to the browser, directly from the database (more or less), will a very low memory footprint.
Upvotes: 1