2013-02-25 70 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