Reputation: 1687
I am querying my db and using the results to create a csv file. Then I put a link on the front-end page to the file that was created on the server like this:
function writetofile($stringData, $myFile) {
$fh = fopen('download/'.$myFile, 'w') or die("can't open file");
fwrite($fh, $stringData);
fclose($fh);
}
$filename = $file."_".date("d-m-Y_H-i",time()).'.csv';
writetofile($seperator, $filename);
print 'Right-click on the link below and select "Save as":' . '<br/><br/>';
print 'Download File: <a href="/download/'.$filename.'" target="_blank">Download Link</a>';
For some reason when I download the file directly from the server it looks correct with all the rows from the db. But, when I go through the steps of what the user will do, i.e. right-click and save, the file only contains the html code from this page.
Upvotes: 3
Views: 13351
Reputation: 10348
UPDATE Take a look at http://php.net/manual/en/function.readfile.php
Put suitable php headers, output file content and exit:
<?php // none space here
function writetofile($stringData, $myFile)
{
if ( ! file_exists('download/' . $myFile))
{
echo 'file missing';
}
else
{
header('HTTP/1.1 200 OK');
header('Cache-Control: no-cache, must-revalidate');
header("Pragma: no-cache");
header("Expires: 0");
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=$myFile");
readfile('download/' . $myFile);
exit;
}
}
In any case investigate http://php.net/manual/en/function.fputcsv.php to assure a correct csv formatting...
Upvotes: 5