I have some PHP code that grabs data from a MySQL db and outputs to CSV. It was working fine but for no apparent reason it’s now printing to the browser screen and not creating a new file with the data. The data being outputted is all fine but I need it to go into a new CSV file.
This is the code (which was working and hasn’t been edited)
if($_POST['exportapproved'])
{
//echo 'Export';
//$result = $_POST['getagencies'];
$result = $mysqli->query('SELECT * FROM certificates WHERE IsApproved LIKE "Y" AND IsVoided NOT LIKE "Y" AND IsArchived NOT LIKE "Y" ORDER BY CertificateID DESC');
if (!$result) { die('Couldn\'t fetch records'); }
$headers = $result->fetch_fields();
foreach($headers as $header) {
$head[] = $header->name;
}
$fp = fopen('php://output', 'w');
ob_end_clean();
if ($fp && $result) {
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="export-approved.csv"');
header('Pragma: no-cache');
header('Expires: 0');
fputcsv($fp, array_values($head));
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
die;
}
}
I read some posts on other forums which suggested changing to the content type, so I have also tried header(“Content-Type: application/ms-excel”) and header(“Content-type: application/octet-stream”); but to no avail.
Any ideas? Thanks!