写入PHP输出缓冲区,然后从缓冲区下载CSV [英] Write to PHP output buffer and then download CSV from buffer

查看:317
本文介绍了写入PHP输出缓冲区,然后从缓冲区下载CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一个CSV文件写入PHP输出缓冲区,然后在完成写入后将该文件下载到客户端计算机。 (我想把它写在服务器上,下载它是工作,但事实证明我不会有生产服务器上的写访问)。

I need to write a CSV file to the PHP output buffer and then download that file to the client's computer after it's done writing. (I wanted to just write it on the server and download it which was working, but it turns out I won't have write access on production servers).

我有以下PHP脚本:

$basic_info = fopen("php://output", 'w');
$basic_header = array(HEADER_ITEMS_IN_HERE);

@fputcsv($basic_info, $basic_header);

while($user_row = $get_users_stmt->fetch(PDO::FETCH_ASSOC)) {
    @fputcsv($basic_info, $user_row);
}

@fclose($basic_info);

header('Content-Description: File Transfer');
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=test.csv');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize("php://output"));
ob_clean();
flush();
readfile("php://output");

我不知道该怎么办。 CSV文件下载,但不显示任何内容。我假设它与我的ob_clean()和flush()命令的顺序有关,但我不知道什么是最好的方式来订购这些东西。

I'm not sure what to do. The CSV file downloads but displays nothing. I assume it has something to do with the ordering of my ob_clean() and flush() commands, but I'm not sure what's the best way to order these things.

任何帮助是值得赞赏的。

Any help is appreciated.

推荐答案

你做的有点太多了。创建脚本的唯一目的是输出CSV。只需将其直接打印到屏幕上。不要担心标头或缓冲区或php://输出或任何类似的东西。

You're doing a little too much. Create the script with the sole purpose of outputting the CSV. Just print it out directly to the screen. Don't worry about headers or buffers or php://output or anything like that yet.

一旦你确认你正在将数据打印到屏幕,只需在开头添加这些标题:

Once you've confirmed that you're printing the data out to the screen appropriately, just add these headers at the beginning:

<?php
header("Content-disposition: attachment; filename=test.csv");
header("Content-Type: text/csv");
?>

...确认相应地下载文件。然后你可以添加其他标题,如果你喜欢(我上面包括的标题是我自己没有任何额外的cruft来获得这个工作,其他的基本上是为了效率和缓存控制,其中一些可能已经被适当处理

... confirm that that downloads the file appropriately. Then you can add the other headers if you like (the headers I included above are those I've used myself without any extra cruft to get this working, the others are basically for efficiency and cache control, some of which may already be handled appropriately by your server, and may or may not be important for your particular application).

如果需要,请使用输出缓冲 ob_start()

If you want, use output buffering with ob_start() and ob_get_clean() to get the output contents into a string which you can then use to fill out Content-Length.

这篇关于写入PHP输出缓冲区,然后从缓冲区下载CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆