douqin2108 2012-06-06 10:56
浏览 202
已采纳

如何导出动态生成的临时csv文件?

I would like to generate a csv file with data, that I get by querying a database. The browser then should prompt the user to download the file. By problem is, that the readfile function needs a filename and not a handle, but I can't find a function to get the filename of this temporary file. I guess there are better ways to do this, but I can't find them.

$handle = tmpfile();
fputcsv($handle, array('year', 'month', 'product', 'count'));
header('Content-Type: application/csv');
header('Content-Disposition:attachment;filename=LS_export');
echo readfile($handle);
fclose($handle);
exit();
  • 写回答

3条回答 默认 最新

  • dsdzz04802 2012-06-06 10:59
    关注

    You are looking for rewind to reset the file pointer to the start of the file, followed by fpassthru to output all the contents of the file.

    rewind($handle);
    fpassthru($handle);
    

    Another solution is to use tempnam to generate a unique file which is not removed when closed. Do not forget to remove it manually when you are done with it.

    $name = tempnam('/tmp', 'csv');
    $handle = fopen($name, 'w');
    ...
    fclose($handle);
    readfile($name);
    unlink($name);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制