Reputation: 1
[Solution found] Thank you all for your replies. I changed the button to a link and it is now working as it should.
I know this subject has been discussed over and over, I've been reading possible solutions the whole day but none solves my problem. I need to make a script to create a csv from mysql data and download the file to the default downloads browser's folder. As I prior said I have tried every possible solution found. I don't have issues in getting the data and putting it in a csv. I will post a simple example from one solution I found here.
<?php
header("Content-Type: text/csv");
header("Content-Disposition: attachment; filename=file.csv");
function outputCSV($data) {
$output = fopen("php://output", "w");
foreach ($data as $row)
fputcsv($output, $row);
fclose($output);
}
outputCSV(array(
array("name 1", "age 1", "city 1"),
array("name 2", "age 2", "city 2"),
array("name 3", "age 3", "city 3")
));
?>
If I put the filename in fopen, like fopen("filename.csv","w") it saves the file in the server. I need to download the file. I believe the problem is in the header. What should I do? Any help is welcomed.
I am using latest versions of xampp, php and trying it on Chrome.
Thank you.
Upvotes: 0
Views: 8573
Reputation: 308
You can use below code to save file in server
fopen("filename.csv","w")
Then you can write code to download saved file by two ways
First
You can read file and pass to browser with headers
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
ob_clean();
readfile($filePath);
exit;
Second
You can redirect to file path like
header("Location: ".SITE_URL."VALID_PATH/filename.csv");
exit;
Upvotes: 0