我正在尝试创建一个简短的 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-Disposition
和 Content-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(即字符串),而不是句柄 - 特别是 basename
、filesize
和 readfile
。所以这些函数调用都不能正常工作。 basename
也不会返回文件扩展名。随心所欲地调用它,即
'Content-Disposition: attachment; filename=data.csv'
正如@Joshua Burns 所说,确保将数组传递给 fputcsv
或使用 assoc
参数。
关于php - 如何下载临时文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15390769/