简体   繁体   中英

Download CSV file from server

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, ie right-click and save, the file only contains the html code from this page.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM