I would like to query a table to a .csv file and automatically download it. The file is created with the appropriate data but the file that is downloaded displays wrong data.
$filename = 'file.csv';
$i=0;
try {
$stmt = $conn->prepare("SELECT DATE, TYPE, AMOUNT, BALANCE FROM TRANSACTIONS WHERE USERNAME=? ORDER BY DATE ASC");
$stmt->execute(array($user));
$num_rows = $stmt->rowCount();
$handle = fopen($filename, 'w+') or die("can't open file");
fputcsv($handle, array('Date','Type','Amount','Balance'));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row2[$i][0] = $row['DATE'];
$row2[$i][1] = $row['TYPE'];
$row2[$i][2] = $row['AMOUNT'];
$row2[$i][3] = $row['BALANCE'];
$i++;
echo $i;
fputcsv($handle, array($row['DATE'], $row['TYPE'], $row['AMOUNT'], $row['BALANCE']));
}
fclose($handle);
header('Content-disposition: attachment; filename='.$filename);
header("Content-Type: application/force-download");
header("Content-Length: " . filesize($filename));
header("Connection: close");
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
This is how the file looks like when it is downloaded in my browser:

Sometimes it looks like this:

And this is how it looks like when it is created on the server:

The file that is created on the server always contain the appropriate structure and data. The file that is downloaded for the user is different and wrong for some reason.
What is wrong with the code?
I typed
instead of