【问题标题】:Force Downloaded CSV File from Server displays the HTML Header script instead, PHP.强制从服务器下载的 CSV 文件显示 HTML Header 脚本,而不是 PHP。
【发布时间】:2016-01-26 18:08:42
【问题描述】:

我的经理交给了我一个 PHP Code-igniter 项目,但我在 PHP 方面没有可靠的经验。我试图从服务器下载一个新创建的 .csv 文件。但是当我下载它时,它没有该文件的内容,而是显示了我的 .html 页面的标题条,我在其中进行了整个编码。

我正在尝试使用强制下载技术,在互联网上都提到过。

$filename = $_SERVER['DOCUMENT_ROOT'] . '/apps/views/style/Default/files/'.'Attendance'.'_'.strtotime("now").'.csv';
$file = $filename;
if (is_file($file) == true) {
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="'.basename($file).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header("Pragma: public", true);
header("Content-Transfer-Encoding: binary");
header('Content-Length: ' . filesize($file));
readfile($file);
      }

此代码在单击按钮时运行,文件确实下载,但它不显示内容,但是当我直接从 Cpanel 服务器手动下载相同的文件时,它有内容。 当我通过此编码下载它时,它具有 html 脚本。

【问题讨论】:

    标签: php download export-to-csv


    【解决方案1】:

    这是因为您在页面内有代码,该页面已经显示了 html 内容或在要显示的缓冲区中,您必须在空白页面内实现强制下载代码或将代码保留在页面顶部,所以它只为您提供文件内容的下载。

    header('Content-type: text/csv');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    
    readfile($file);
    

    【讨论】:

      猜你喜欢
      • 2019-09-25
      • 1970-01-01
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2012-05-19
      • 2023-03-25
      • 2012-07-09
      • 2012-01-18
      相关资源
      最近更新 更多