【问题标题】:Download CSV file from server从服务器下载 CSV 文件
【发布时间】:2013-01-01 06:26:10
【问题描述】:

我正在查询我的数据库并使用结果创建一个 csv 文件。然后我在前端页面上放了一个链接,指向在服务器上创建的文件,如下所示:

function writetofile($stringData, $myFile) {
     $fh = fopen('download/'.$myFile, 'w') or die("can't open file");
     fwrite($fh, $stringData);
     fclose($fh);
}

$filename = $file."_".date("d-m-Y_H-i",time()).'.csv';

writetofile($seperator, $filename);
print 'Right-click on the link below and select "Save as":' . '<br/><br/>';
print 'Download File: <a href="/download/'.$filename.'" target="_blank">Download Link</a>'; 

由于某种原因,当我直接从服务器下载文件时,数据库中的所有行看起来都是正确的。但是,当我完成用户将要执行的操作(即右键单击并保存)的步骤时,该文件仅包含此页面中的 html 代码。

【问题讨论】:

  • 如果你只是点击链接而不是右键另存为怎么办?
  • 不需要target="_blank" - 虽然我怀疑这会解决你的问题?
  • $seperator的值是多少?
  • $file 的值是多少? (即向我们展示所有相关代码)
  • 这个脚本大概是在文档根目录下运行的吧?

标签: php csv


【解决方案1】:

更新看看http://php.net/manual/en/function.readfile.php

放置合适的php头文件,输出文件内容并退出:

<?php // none space here
function writetofile($stringData, $myFile)
{
    if ( ! file_exists('download/' . $myFile))
    {
        echo 'file missing';
    }
    else
    {
        header('HTTP/1.1 200 OK');
        header('Cache-Control: no-cache, must-revalidate');
        header("Pragma: no-cache");
        header("Expires: 0");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=$myFile");
        readfile('download/' . $myFile);
        exit;
    }
}

无论如何调查http://php.net/manual/en/function.fputcsv.php 以确保正确的 csv 格式...

【讨论】:

  • @mg1 你准备好了吗?我建议您从专用文件中输出 csv...(而不是您链接它)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-13
  • 2017-03-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多