我有一个通用的php函数,它访问资源并将其下载为csv文件,resourcee是一个文件或php://memory.如何找到此资源的大小,以便设置标题内容长度
/** Download a file as csv and exit */
function downloadCsv($filName, $fil) {
header("Content-Type: application/csv");
header("Content-Disposition: attachement; filename=$filName");
// header("Content-Length: ".......
fpassthru($fil);
exit;
}
我可以看到如何使用filesize($filename)从文件名中获取文件大小,但在这个函数中,我不知道/没有文件名,只是一个资源
fstat()可以完成以下任务:
$stat = fstat($fil);
header('Content-Length: '.$stat['size']);
只需使用php://temp/或php://memory/
php://参考
/** Download a file as csv and exit */
function downloadCsv($filName, $fil) {
header("Content-Type: application/csv");
header("Content-Disposition: attachement; filename=$filName");
//here the code
$tmp_filename = 'php://temp/'.$filName;
$fp = fopen($tmp_filename,'r+');
fwrite($fp, $fil);
fclose($fp);
header("Content-Length: ".filesize($tmp_filename)); //use temp filename
readfile($fil);
exit;
}