php - 如何下载临时文件

标签 php

我正在尝试创建一个简短的 PHP 脚本,该脚本采用 JSON 字符串,将其转换为 CSV 格式(使用 fputcsv),并使该 CSV 可作为下载的 .csv 文件使用。我的想法是使用 tmpfile() 来不用担心 cronjobs 或磁盘空间不足,但我似乎无法让奇迹发生。

这是我的尝试,它是来自 the PHP docs of readfile 的转换示例:

$tmp = tmpfile();
$jsonArray = json_decode( $_POST['json'] );
fputcsv($tmp, $jsonArray);

header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename='.basename($tmp));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmp));

ob_clean();
flush();
readfile($tmp);

我觉得 Content-DispositionContent-Transfer-Encoding header 有误,但我不确定如何修复它们。例如,basename($tmp) 似乎没有返回任何内容,而且我不确定 text/csv 是否以二进制编码传输。同样,echo filesize($tmp) 也是空白的。有没有办法做我在这里尝试的事情?

[编辑]

**以下是我根据接受的答案编写的工作代码:*

$jsonArray = json_decode( $_POST['json'], true );
$tmpName = tempnam(sys_get_temp_dir(), 'data');
$file = fopen($tmpName, 'w');

fputcsv($file, $jsonArray);
fclose($file);

header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=data.csv');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($tmpName));

ob_clean();
flush();
readfile($tmpName);

unlink($tmpName);

最佳答案

请注意 tmpfile() 返回一个文件句柄,但您拥有的所有函数都需要一个文件 path(即字符串),而不是句柄 - 特别是 basenamefilesizereadfile。所以这些函数调用都不能正常工作。 basename 也不会返回文件扩展名。随心所欲地调用它,即

'Content-Disposition: attachment; filename=data.csv'

正如@Joshua Burns 所说,确保将数组传递给 fputcsv 或使用 assoc 参数。

关于php - 如何下载临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390769/

相关文章:

php - 如何在 php 中将电子邮件地址分成不同的部分?

php - 在mysql中将一个元组输入到一个表中

php - SQL 语句在 SUM() 函数上停止运行

javascript - 也许 PHP 还记得颜色?

php - mysql错误: could not start the service mysql on local computer error 193: oxc1

php - 如何在 PHP 中的多个 get 请求之间共享对象?

php - 以特定的 html 结构显示一些简单和可变产品的数据

php - 如何在 php 中检查字符串是否包含 { 和 } 等特殊字符

php - 如何在网页中显示邮件内容?

php - Ember CLI : index. php 而不是 index.html