我正在尝试在我的php脚本中创建一个CSV文件。它创建文件,但每次在末尾插入一个空行。
我的代码如下:
$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;
无论我的数据库查询是什么或csv包含多少行,最后总会有一个空行。是否有任何原因造成这种情况?
答案 0 :(得分:1)
您可以将CSV直接写入输出,并且您不需要自己格式化。
// 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);
另一个好处是它会在大量下载时使用更少的内存,例如使用PDO:
$stmt = $pdo->prepare("SELECT ...");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
fputcsv($fp, $row);
}
这将直接从数据库(或多或少)输出每一行到浏览器,将占用非常低的内存。
答案 1 :(得分:0)
除了Mark Baker突出显示的其他问题外,您还在循环中添加EOL
。通过trim
print trim($csv_output);