fputcsv inserting empty row in beginning of .csv

情到浓时终转凉″ 提交于 2019-12-23 12:57:08

问题


<?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.


回答1:


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



来源:https://stackoverflow.com/questions/16610821/fputcsv-inserting-empty-row-in-beginning-of-csv

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!