【发布时间】:2013-03-13 16:18:02
【问题描述】:
我正在尝试创建一个简短的 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 标头是错误的,但我不确定如何修复它们。例如,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);
【问题讨论】:
-
有关此问题的 javascript 解决方案,请查看stackoverflow.com/questions/4130849/…。
-
json_decode是否会返回null? -
所以文件只是不想被下载?并在浏览器中打开?这就是问题所在?
标签: php