简体   繁体   English

PHP / MYSQL到CSV将代码打印输出到屏幕而不是CSV文件

[英]PHP/MYSQL to CSV Export code printing to screen instead of CSV file

I can't get the browser to prompt for download. 我无法让浏览器提示下载。 The output gets displayed on the screen instead. 输出将改为显示在屏幕上。 I've tried so many other threads regarding this topic on this site but to no avail. 我在此站点上尝试了许多与此主题相关的其他主题,但均无济于事。 I could change the fopen("php://output","w") to fopen("export.csv","w") but that will save a copy of the export.csv file on the server, which I don't want. 我可以将fopen("php://output","w")更改为fopen("export.csv","w")但这将在服务器上保存export.csv文件的副本,不想。 I want the file to be downloaded on the client without it being saved on the server. 我希望将文件下载到客户端而不将其保存在服务器上。 Here's my code: 这是我的代码:

$sql = mysql_query($_SESSION["export-query"]);
$fields = mysql_num_fields($sql);
$header = array();

for ($i = 0; $i < $fields; $i++) {
    $header[] = mysql_field_name($sql, $i);
}

$f = fopen("php://output","w"); 
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=export.csv');
header('Pragma: public');
header('Expires: 0');
header('Cache-Control: must-revalidate');
fputcsv($f, $header);

while ($row = mysql_fetch_row($sql)) {
    fputcsv($f, $row);
}
fclose($f);

Please help! 请帮忙! Much appreciated. 非常感激。

Your code is really close to mine, but I have this 您的代码确实很接近我,但是我有这个

header("Content-type: application/vnd.ms-excel");

for the content type. 用于内容类型。 I think this works because browsers know how to handle text/csv but they don't know how to handle excel. 我认为这可行,因为浏览器知道如何处理text / csv,但他们不知道如何处理excel。 It will prompt to download because it doesn't open this type of file itself. 它将提示下载,因为它本身不会打开此类文件。

I also don't have "must-revalidate," but I don't think that makes a difference. 我也没有“必须重新验证”,但我认为这没有什么不同。

EDIT: 编辑:

Here are my full headers, which have worked 100% of the time. 这是我的完整标头,它们在100%的时间内都有效。 There are minor differences from yours, so maybe one of them is the reason. 与您之间的差异很小,所以也许其中一个是原因。

    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: attachment; filename=".$filename.".csv");
    header("Pragma: no-cache");
    header("Expires: 0");

EDIT 2: 编辑2:

Judging from your comment on your answer, you are putting all of this code as an ajax call inside a div. 从您对答案的评论来看,您会将所有这些代码作为ajax调用放入div中。 The reason that doesn't work is that you can only set headers on the initial call to a page. 不起作用的原因是,您只能在页面的初始调用上设置标题。 Setting headers on an ajax call will be ignored. 在ajax调用上设置标头将被忽略。

Here is how my system handles csv generation. 这是我的系统处理csv生成的方式。 Because I needed specific information that could vary between different csv files, I put the name of the generator file into the "action" of a form and provided a submit button: 因为我需要在不同的csv文件之间可能有所不同的特定信息,所以我将生成器文件的名称放入表单的“操作”中并提供了一个提交按钮:

<form action="thegeneratorpage.php" method="get"><fieldset>
     <p>Download [...] in .csv (Excel) form.  You can narrow by [...].</p>
     <!-- code here that allows users to narrow down what is in the csv -->
     <input type="submit" value="Download" />
</fieldset></form>

If the information doesn't vary, you can just do this: 如果信息不变,则可以执行以下操作:

<a href="thegeneratorpage.php">Download CSV</a>

All the code we have been discussing would be on thegeneratorpage.php . 我们一直在讨论的所有代码都在thegeneratorpage.php

Rather than using the fputcsv function, I would suggest just echoing the rows of the CSV file like so (note that the headers I use are slightly different from yours): 建议不要使用fputcsv函数,而是像这样回显CSV文件的行(请注意,我使用的标头与您的标头略有不同):

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename={$fileName}");
header("Content-Transfer-Encoding: binary");
while ($row = mysql_fetch_row($sql)) {
    // optionally enclose data if necessary
    foreach ($row as $k => $v) {
        if (strpos($v, ',') !== false) {
            $row[$k] = '"' . $v . '"';
        }
    }
    echo implode(',', array_values($row));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM