CSV MIME 类型无法通过浏览器下载的问题


Issue with CSV MIME Type not downloading through browser

所以,首先让我声明一下,在您开始提供有关如何简单地将完整表导出到 CSV 文件的其他建议之前,这不是我想要做的(我现在的演示代码建议,但我只是通过浏览器 shabaz 测试整个下载)。

我实际上想构建要从多个表中导出的内容。 无论如何,我只是想通过浏览器进行导出和下载。

我从在线示例中获得此代码,目前正在发生的事情是它只是将数据打印到我的浏览器。

这是我正在测试的代码:

$result = mysql_query("SELECT * FROM results_tb") or die(mysql_error());
    // I hard-code the column names so I can capitalize, add spaces, etc.
    $fields = '"User ID","Test_id","score %","Time taken"'."'n";
    // Iterate through the rows of data
    while ($row = mysql_fetch_assoc($result))
    {
        //echo $row['user_id'];
        $fields .= '"'.$row['user_id'].'","'.$row['test_id'].'","'.$row['score'].'","'.$row['time_elapsed'].'"'."'n";
    }
    // Set our headers
    header('Content-type: text/csv');
    // To display data in-browser, change the header below to:
    // header("Content-Disposition: inline");
    header("Content-Disposition: attachment; filename=event_registrations.csv");
    // Output our data
    echo $fields;

假设这个例子是裤子,所以有人可以向我解释如何做到这一点吗?

非常感谢:D

我的标题响应被Firebug-Lite捕获:

Date    Wed, 18 May 2011 14:15:18 GMT
X-Powered-By    PHP/5.1.6
Content-disposition attachment;filename=MyVerySpecial.csv
Connection  close
Content-Length  992
Server  Apache/2.2.3 (Red Hat)
Content-Type    text/csv

我的猜测是,你已经display_errors设置了,并且在发出这些header()调用之前输出了一些东西。这会导致您看到的行为。

首先,编辑您的php.ini文件并确保display_errors已打开,并且您在 PHP 脚本中报告时有错误(例如 error_reporting(E_ALL);)。现在您可能会在屏幕上看到错误。大致如下:

Cannot send header information. Output already started by XXX.php (line YYY).

可能发生的情况是,您在发送header()命令之前不小心发送了一个空格或换行符,并且您正在抑制错误。当您在这些header()调用之前向浏览器发送内容时,它们将被忽略。因此,浏览器只会显示您发送的任何内容,而不是让用户下载它。

如果您使用的是 Firefox,您还可以使用 Firebug 扩展来检查下载的 HTTP 响应标头。