Question

I'm trying to download a CSV file through the browser. The script is partially working, because so far I managed to display the CSV on screen, but the download is not starting.

Here is what i tried so far:

if(isset($currency)) {
    header("Content-Type: application/csv");
    header("Content-Disposition: attachment;Filename=Pricelogs.csv");
    ob_clean();
    $filename = "/tmp/".uniqid().".csv";
    exportCSVFile($filename, $currency, $country, $provider);
    readfile($filename);
    //unlink("'".$filename."'");
} else {
    echo "ERR_USERNAME_PASSWORD";
    exit();
}

I had already read all questions of this type from FAQ & also tried but it gets open on browser only,instead of downloading.
I had also used header with single quotes. I also tried header("Content-Type: text/csv"); Also:

    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Cache-Control: private",false); // required for certain browsers 
    header("Content-Type: application/force-download");
    header("Content-Disposition: attachment; filename=\"".$filename."\";" );
    header("Content-Transfer-Encoding: binary");
Was it helpful?

Solution

PUT your CSV file URL, it will display in browser in place of force browser to download. You can open it in iframe in your site.

http://docs.google.com/viewer?embedded=true&url=www.yoursite.com/filename.csv

OTHER TIPS

I usually just do:

header('Content-type: text/csv');
header("Content-Disposition: attachment; filename=my_csv_filename.csv");

// print CSV lines here

exit();

I can tell you this combination is working for me:

$bom = chr(0xEF) . chr(0xBB) . chr(0xBF);
header("Content-type: application/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename=$filename.csv");
header("Pragma: no-cache");
header("Expires: 0");
print $bom . $data;
exit;

If I were you, I would first test this plainly (outside of all your buffering), first see that you manage to make this work, and only then test it in your specific set up.

You might try this.

header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename.csv\";" );

print $content;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top