I want to create and download a CSV file, in one script.
Up to now I have been avoiding my lack of knowledge by pre-creating the file with a cron job and then downloading the file via a link.
I have this:
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die ('Error connecting to mysql');
$get_members_csv_query = "SELECT * FROM members";
$get_members_csv_result=$conn->query($get_members_csv_query, MYSQLI_STORE_RESULT);
$all_members_array = array();
while ($get_members_csv_array = $get_members_csv_result->fetch_assoc())
{
array_push($all_members_array, $get_members_csv_array);
}
$file = fopen('members.csv', 'w');
fputcsv($file, array('email', 'First Name', 'Surname', 'Gender','DOB','Registered On','Country','paid','Children','Wants Kids','Relationship','Body Type','Height','Smoke','Drink','Phone','Region','Religion','Community'));
foreach ($all_members_array as $row) {
fputcsv($file, $row);
}
exit();
This creates the file successfully, but what do I need to add to the script to make it automatically download the CSV file once created?
I have tried putting this at the start if the script:
header("Content-type: text/csv");
header("Content-Disposition: attachment; filename=members.csv");
header("Pragma: no-cache");
header("Expires: 0");
But it downloads the file before the script finishes (or even starts) creating the file.
I have tries putting the headers at the end of the script and using ob_start() at the top - same result.
Thanks