Jump to content

PHP Script That Creates Text File for Download


mike102t

Recommended Posts

Hello I have a php script I actually got from Stackoverflow, on one of the questions asked. I'm not really sure where to apply it, I put it in some code that I had already that submits the data to be put in the text file. It downloads the file, but inside it has php errors. 
 
The errors are:
 
    Undefined variable: month in xxx.xxx.xxx on line 12
    Undefined variable: res xxx.xxx.xxx on line 14
    mysql_fetch_array() expects parameter 1 to be resource, null given in  xxx.xxx.xxx on line 14
 
The script I have is: 
 
    //Below is where you create particular month's text file
    $file = $month . '.txt';
    $handle = fopen($file, "w");
    while ($row=mysql_fetch_array($res)){
        $writestring = $row['data_I_want'] . "\r\n";
        fwrite($handle, $writestring);
    }
    fclose($handle);
    $data = file_get_contents($file);
     echo $data;
    //Now the file is ready with data from database
    
    //Add below to download the text file created
    $filename = $file; //name of the file
    $filepath = $file; //location of the file. I have put $file since your file is create on the same folder where this script is
    header("Cache-control: private");
    header("Content-type: application/force-download");
    header("Content-transfer-encoding: binary\n");
    header("Content-disposition: attachment; filename=\"$filename\"");
    header("Content-Length: ".filesize($filepath));
    readfile($filepath);
    exit;

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.