2016-09-29 37 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