prepare($query); require('http_errors.php'); if (!$statement->execute()) { HttpResponse::internal_server_error()->set_and_exit(); } $out = fopen('php://output', 'w'); if ($out === false) { HttpResponse::internal_server_error()->set_and_exit(); } if (substr($filename, -4) !== '.csv') { $filename = $filename . '.csv'; } header('Content-Type: text/csv'); header('Content-Disposition: filename=' . $filename); if ($print_header) { $columns = array(); for ($i = 0; $i < $statement->columnCount(); $i++) { $columns[] = $statement->getColumnMeta($i)['name']; } fputcsv($out, $columns); } while ($row = $statement->fetch(PDO::FETCH_NUM)) { fputcsv($out, $row); } }