php 写一个文本文件,用php强制下载
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11903436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 02:25:05 来源:igfitidea点击:
Write a text file and force to download with php
提问by stevey
Im using a button to direct to a script which creates a text file:
我使用按钮指向创建文本文件的脚本:
<?php
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
?>
after that I want the web browser to propose to download or open this file how should I do? Thanks
之后我想让网页浏览器建议下载或打开这个文件,我该怎么办?谢谢
回答by Mihai Iorga
use readfile()and application/octet-streamheaders
使用readfile()和application/octet-stream标题
<?php
$handle = fopen("file.txt", "w");
fwrite($handle, "text1.....");
fclose($handle);
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename('file.txt'));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize('file.txt'));
readfile('file.txt');
exit;
?>
回答by Edson Medina
$content = file_get_contents ($filename);
header ('Content-Type: application/octet-stream');
echo $content;
Should work
应该管用

