【问题标题】:Not able to generate CSV file with php无法使用 php 生成 CSV 文件
【发布时间】:2018-05-04 10:37:55
【问题描述】:

我想使用 php 下载 csv 文件。这就是我所做的

    $filename = $reportof . '.csv';

    header('Content-type: text/csv');
    header('Content-Disposition: attachment; filename="' . $filename . '";');
    $f = fopen('php://output', 'w');
    $delimiter = ";";

    fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
    foreach ($Reports as $line) {
        fputcsv($f, $line, $delimiter);
    }

这里的 $Reports 包含我想要的 CSV 文件中的所有数据。 当我检查控制台-> 网络时,我得到了这些数据作为响应。 但是文件没有被下载。 谁能建议我哪里出错了?

【问题讨论】:

    标签: php csv export-to-csv


    【解决方案1】:

    尝试使用 window.open 打开带有 URL 的新浏览器窗口。浏览器可能不会让客户端通过 AJAX 请求打开屏幕。 另一个原因可能是您的浏览器试图在查看器中显示文件,但它无法这样做。换个浏览器试试?

    但是,这仍然是猜测,因为您在检查器的网络选项卡中看到内容,而不是向我们展示您如何调用脚本...

    【讨论】:

      【解决方案2】:

      完成写入后,请务必关闭文件指针。

      $filename = $reportof . '.csv';
      
      header('Content-Description: File Transfer');
      header('Content-type: text/csv');
      header('Content-Disposition: attachment; filename="' . $filename . '";');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      
      $f = fopen('php://output', 'w');
      ob_clean();
      
      $delimiter = ';';
      
      fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
      foreach ($Reports as $line) {
          fputcsv($f, $line, $delimiter);
      }
      
      ob_flush();
      fclose($f);
      die();
      

      编辑:

      添加了ob_clean()ob_flush() 方法,这只是为了确保缓冲区中的任何输出都被清除,如果之前没有写入任何内容可以跳过

      编辑 2:

      添加了一些虚拟数据进行测试,这行得通。

      header('Content-Description: File Transfer');
      header('Content-type: text/csv');
      header('Content-Disposition: attachment; filename="test.csv";');
      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
      
      $f = fopen('php://output', 'w');
      
      $delimiter = ';';
      
      $rs = [
          [1, 'some name1', 'open', date('c'), 1],
          [2, 'some name2', 'closed', date('c'), 2],
          [3, 'some name3', 'open', date('c'), 3],
          [4, 'some name4', 'closed', date('c'), 4],
          [5, 'some name5', 'open', date('c'), 5],
      ];
      
      fputcsv($f, array('ID', 'Name', 'Status', 'Date', 'Rank'));
      foreach ($rs as $line) {
          fputcsv($f, $line, $delimiter);
      }
      
      fclose($f);
      die();
      

      这会自动下载 csv:

      【讨论】:

      • 它返回与以前没有下载 CSV 文件相同的输出。
      • @rohitraut 然后我会检查你的代码,添加(另一个)工作示例作为编辑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-29
      相关资源
      最近更新 更多