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;

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.