【问题标题】:Exporting data using fputcsv won't download使用 fputcsv 导出数据不会下载
【发布时间】:2014-11-20 15:17:57
【问题描述】:

我在尝试导出数据和下载 CSV 时遇到了一个非常奇怪的问题。

问题是,当我点击大约 30 行时,浏览器决定显示数据而不是下载到文档中。起初我以为是数据,但在故障排除过程中,我通过导入相同的文档进行了测试。

导入一次,我的下载就会触发并完美运行。再次导入并复制数据,突然间它显示它而不是下载它。

这不是一个大文件,但我可以设置某种大小或字符限制吗?我尝试了几种故障排除方法,但不确定该去哪里,因为它工作到一定限度。

    $group = "";
    ob_start();
    $group = fopen('php://output', 'w');
    fputcsv($group, array_keys(rest($groups[0])));
    foreach ($groups as $result) {
        fputcsv($group, $result);
    }
    fclose($group);
    return ob_get_clean();

    $response = $this->getResponse();
    $headers = $response->getHeaders();
    $headers->addHeaderLine('Content-Type', 'application/download');
    $headers->addHeaderLine('Content-Type', 'text/csv');
    $headers->addHeaderLine('Content-Disposition', "attachment; filename=\"my_filen.csv\"");
    $headers->addHeaderLine('Accept-Ranges', 'bytes');
    $headers->addHeaderLine('Content-Length', strlen((string)$group));

    return $response;

如果有帮助,我正在运行 Zend 框架 2。

【问题讨论】:

  • 为什么要打扰接受范围,因为您的代码实际上并不做字节服务?另外,设置两种内容类型是没有意义的。第二个是覆盖/替换第一个。你基本上是在做“这是香蕉。这是法拉利”。 return ob_get_clean() 无论如何都会终止代码,并且执行永远不会到达整个 $headers 业务。
  • 感谢 Marc,您说的非常对。这里有一堆额外的代码,因为我只是试图排除故障,看看是否有一些东西没有被正确读取,或者做了任何改变。一旦我解决了它,我一定会清理它。

标签: php zend-framework2 export-to-csv


【解决方案1】:

我认为这可能与 php.ini 或 gzip 编码中的刷新设置有关。

您可以改为将其写入文本文件,然后强制下载该文件。

<?php
    $handle = fopen("somefile.txt", "w");
    fwrite($handle, "your content here");
    fclose($handle);

    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename('somefile.txt'));
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize('somefile.txt'));
    readfile('somefile.txt');
    exit;
?>

或者如果你可以在你的服务器中使用它:

$content = file_get_contents ($filename);
header ('Content-Type: application/octet-stream');
echo $content;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    • 2021-03-14
    • 2013-06-27
    • 2020-05-07
    • 1970-01-01
    相关资源
    最近更新 更多