2016-09-29 33 views
1

我正在導入數據在我的數據庫中,我想提供一些錯誤/反饋給用戶在文本文件中,但我不知道如何處理它。我的代碼是很長,所以我會把一個示例代碼文件PHP寫入文件並上傳到屏幕

<?php 
$myfile = fopen("newfile.txt", "w") or die("Unable to open file!"); 
$txt = "John Doe\n"; 
fwrite($myfile, $txt); 
$txt = "Jane Doe\n"; 
fwrite($myfile, $txt); 
fclose($myfile); 
?> 

寫在這種情況下,我會想「李四」兩次在我的文件並上傳到屏幕上,以便用戶可以下載它

回答

1

您可以使用php readfile()發送文件到輸出緩衝區。你可以看一看關於如何做到這一點的例子的PHP文檔。 Readfile()

樣品看起來像這樣

if (file_exists($myfile)) { 
    header('Content-Description: File Transfer'); 
    header('Content-Type: application/octet-stream'); 
    header('Content-Disposition: attachment; filename="'.basename($myfile).'"'); 
    header('Cache-Control: must-revalidate'); 
    header('Content-Length: ' . filesize($myfile)); 
    readfile($myfile); 
    exit; 
} 
0

你可以試試下面的代碼片段:

<?php 

    $fileName  = "data-log.txt"; 

    // IF THE FILE DOES NOT EXIST, WRITE TO IT AS YOU OPEN UP A STREAM, 
    // OTHERWISE, JUST APPEND TO IT... 
    if(!file_exists($fileName)){ 
     $fileMode = "w"; 
    }else{ 
     $fileMode = "a"; 
    } 

    // OPEN THE FILE FOR WRITING OR APPENDING... 
    $fileHandle  = fopen($fileName, $fileMode) or die("Unable to open file!"); 
    $txt   = "John Doe\n"; 
    fwrite($fileHandle, $txt); 

    $txt   = "Jane Doe\n"; 
    fwrite($fileHandle, $txt); 
    fclose($fileHandle); 


    // PUT THE FILE UP FOR DOWNLOAD: 
    processDownload($fileName); 

    function processDownload($fileName) { 
     if($fileName){ 
      if(file_exists($fileName)){ 
       $size = @filesize($fileName); 
       header('Content-Description: File Transfer'); 
       header('Content-Type: application/octet-stream'); 
       header('Content-Disposition: attachment; filename=' . $fileName); 
       header('Content-Transfer-Encoding: binary'); 
       header('Connection: Keep-Alive'); 
       header('Expires: 0'); 
       header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); 
       header('Pragma: public'); 
       header('Content-Length: ' . $size); 
       readfile($fileName); 
       exit; 
      } 
     } 
     return FALSE; 
    } 
?> 
+0

對於一些原因,我不斷收到'無法打開文件'-_____- – Bobby