开发者

Create a CSV file with PHP via fopen/fwrite but also write headers to it

I feel like I am missing obvious here, but I will post anyway.

I have a 'csv.php' which creates a csv file, simple example:

// csv.php
$fh = fopen('report.csv', 'w') or die("can't open file");
while ($row = mysql_fetch_row($result)) { 
    fputcsv($fh, $row);
}
fclose($fh);

On a seperate page, there is a simple anchor element that links to the file above. So on home.html there is:

<a href='report.csv'>Re开发者_StackOverflowport</a>

One user will run csv.php and another will goto home.html and click the link at a later point in time. This works fine, the CSV is created, the data is there, and the anchor links through.

I know that if I were echoing out the CSV, I would add the various headers such as:

header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

But how do I add these headers to the file report.csv? I assume this is required because firefox refuses to see the csv as a downloadable file (when the anchor is clicked, it just outputs the csv to the browser).


You won't be able to add the headers to the report.csv itself. You can alternately have a proxying script, something like download.php?report=report.csv

Then, you would do something like the following:

$csv = file_get_contents("./csv_directory/" . preg_replace("#/#", "", $_GET['report']);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $csv;

Big Note
As @Pat mentioned (while I was looking for the appropriate syntax), you can use .htaccess or modify httpd.conf itself if you are using apache and have access. This, in my opinion, is a better way to solve your problem.


Headers aren't part of a file, they're part of an HTTP response.

If your web server is not setting the headers you want for csv files, you can probably convince it to do so.

Or, if you can't (or don't want to), see sberry2A's answer, to serve the file via php, and control the web server that way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜