2013-02-25 68 views
3

我正在研究如何从字符串创建文件的方法,这可能是纯文本将保存为.txt和PHP为.php等,但我希望得到一些洞察到它写入字符串文件并强制在PHP下载

**我发现这个代码

$file = 'people.txt'; 
// Open the file to get existing content 
$current = file_get_contents($file); 
// Append a new person to the file 
$current .= "John Smith\n"; 
// Write the contents back to the file 
file_put_contents($file, $current); 

但是我需要有救了我的服务器上people.txt?

力下载部分

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\""); 
header("Content-Type: application/force-download"); 
header("Content-Length: " . filesize($File)); 
header("Connection: close"); 

哪里需要房子上面,我假设的代码是正确的,迫使我下载现成的文件?

+0

简短的回答:不,你并不需要先创建一个文件。无论你在阅读不存在的文件。看看'fopen($文件,'w +')'而不是。之后,您只需在强制下载标题后回显您的字符串。 – h2ooooooo 2013-02-25 09:45:36

回答

19

您不需要将字符串写入文件以便将其发送到浏览器。请看下面的例子,它会提示你的UA尝试下载一个名为“sample.txt的”含$ str中的值文件:

<?php 

$str = "Some pseudo-random 
text spanning 
multiple lines"; 

header('Content-Disposition: attachment; filename="sample.txt"'); 
header('Content-Type: text/plain'); # Don't use application/force-download - it's not a real MIME type, and the Content-Disposition header is sufficient 
header('Content-Length: ' . strlen($str)); 
header('Connection: close'); 


echo $str; 
+0

如何停止下载。即如果我的程序发送一个文件,然后需要发送更多的输出到浏览器?或者那是不可能的? – 2015-02-27 22:16:16

+0

HTTP我没有提供今天的设施,我知道。 – TML 2015-02-27 23:03:30

+0

假设此下载代码在将输出发送到浏览器的其他代码之前执行。如何防止将更多输出放入下载文件?有些答案说要添加'exit();'但如果你有一些日志代码或者其他不想切断的东西,那是不可行的。 – 2015-02-27 23:05:26