2012-12-12 25 views
0

我有一個文件,index2.php已被寫入一個表單。在PHP中彈出另存爲對話框

這個文件的全部內容,我已經存儲在一個變量$final_code使用輸出緩衝區。

我現在希望在頁面末尾添加一個「下載」按鈕,這會彈出另存爲對話框,允許用戶將該文件的源代碼(即變量)保存爲.txt - 但是我「難倒了。

index2.php:

<?php 

// Start buffering the output 
ob_start(); 

?> 

<!-- INDEX2.PHP HTML ELEMENTS HERE --> 

<?php 
// Store the contents of the buffer 
$final_code = ob_get_contents(); 

// Print the contents of the buffer 
ob_end_flush(); 
?> 

<form action="savefile.php" method="post"> 

Happy? Save this to file: <input type="submit" name="savefile" value="Save" /> 

</form> 

我不知道這是否需要這個文件或savefile.php進行工作,所以後者目前是空白。

+0

看到[這個SO問題](http://stackoverflow.com/questions/4458119/display-save-as-dialog-and-save-contents-of-a-selected-text-inside-textarea-to) – jaudette

回答

4

我認爲你不能在瀏覽器中強制另存爲文件對話框。

爲forceing一個txt文件,我做以下的下載:

header('Pragma: anytextexeptno-cache', true); 
header("Pragma: public"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("Cache-Control: private", false); 
header("Content-Type: text/plain"); 
header("Content-Disposition: attachment; filename=\"example.txt\""); 
echo $output; 

希望幫助。

0

你正在尋找PHP下載腳本(從瀏覽器)?

1

您需要使用頭文件強制下載:

$file = 'somefile.zip'; 

if(!file) 
{ 
    // File doesn't exist, output error 
    die('file not found'); 
} 
else 
{ 
    // Set headers 
    header("Cache-Control: public"); 
    header("Content-Description: File Transfer"); 
    header("Content-Disposition: attachment; filename=$file"); 
    header("Content-Type: application/zip"); 
    header("Content-Transfer-Encoding: binary"); 

    // Read the file from disk 
    readfile($file); 
} 

舉例摘自: http://www.ryboe.com/tutorials/php-headers-force-download

見鏈接作進一步的解釋。

+0

如何得到這個文件中變量'$ final_code'的內容?謝謝。 – mpdc

+1

用「echo $ final_code」替換「readfile()」 – steven

+0

這給了我一個「壓縮(壓縮)文件夾無效或損壞。」錯誤 - 它也運行在** index2.php **頁面加載,而不是按鈕單擊... – mpdc