PHP fread 在成功 fopen、write 和 fclose 后无法工作
现在是凌晨,我只是没有得到这个:
以下代码可以工作,并且文件被放置在服务器上:
$filename = $ioid . "_" . time();
$fp = fopen("$filename.csv", "w+");
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
但这之后不起作用(文件为 105k):
$fp2 = fopen("$filename.csv", "r");
$output = fread($fp2, 1000000000000);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
fclose($fp2);
没有读取任何内容,也没有打印任何内容页面。
我做错了什么明显的事情? :)
It's early in the morning and I'm just not getting this:
The following code works, and file is placed on the server:
$filename = $ioid . "_" . time();
$fp = fopen("$filename.csv", "w+");
foreach ($csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
But this doesn't work straight after (file is 105k):
$fp2 = fopen("$filename.csv", "r");
$output = fread($fp2, 1000000000000);
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
echo $output;
fclose($fp2);
Nothing is read, and nothing is printed to the page.
What obvious thing am I doing wrong? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是
fread($fp2, 1000000000000)
尝试分配 1 TB 大缓冲区来读入文件,并且显然达到了允许的内存限制,除非您使用的是发生整数溢出的 32 位平台。不管怎样,它都不起作用。如果您想将整个文件读取到输出缓冲区并快速完成,请像这样使用
readfile()
:下次一定要检查错误日志。
另外,如果您不打算将生成的文件存储在磁盘上,我建议您重新制作脚本以使用更安全的方法:
Your problem is that
fread($fp2, 1000000000000)
tries to allocate 1 terabyte big buffer to read the file into and obviously hits allowed memory limit, unless you're on a 32-bit platform where integer overflow occurs. Either way it isn't working.If you want read a whole file to the output buffer and do that fast, use
readfile()
like so:Be sure to check the error log next time.
Also if you don't plan to store resulting files on disk I recommend you to remake your script to use a safer approach:
问题出在
fread
参数中。您的代码会产生:例如,当将 1000000000000 更改为 1000 时,它会起作用。所以:这样使用它:
The probkem is in
fread
argument. Your code produces:when changing 1000000000000 to 1000 for example it works. so: use it this way: