Hi,
I have a script which creates a csv from a database and is supposed to offer the csv as a download. The csv is created on the server. However, the csv is not offered as a download.
Here is my code:
<?php
class CSVExport
{
public function __construct()
{
require_once 'Zend/Date.php';
require_once 'DatabaseConnection.php';
}
public function exportCSV($query)
{
$result = mysql_query($query);
$fname = 'CSVFile.csv';
$headers = array();
$rowArray = array();
$numFields = mysql_num_fields($result);
$numRows = mysql_num_rows($result);
for ($i = 0; $i < $numFields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
$fp = fopen($fname, 'w');
if ($fp && $result) {
header("Pragma: no-cache");
header("Cache: no-cache");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Type: application/csv");
header("Content-Disposition: attachment; filename=".$fname);
header("Content-Transfer-Encoding: binary");
fputcsv($fp, $headers);
while ($thisrow = mysql_fetch_row($result)) {
fputcsv($fp, $thisrow);
}
readfile($fname);
fclose($fp);
}
die('file not found');
}
}
I have tried other Content-Types such as text/csv and application/excel but a download dialog still isnt offered.
As a workaround, I set a navigateToURL in Flash which links to the csv file on the server. This works fine in IE 8 and a download dialog is offered. However, in Firefox and Google Chrome, the csv file is displayed within the browser which is not what I need.
Im a beginner in PHP so any help as to where im going wrong is much appreciated.
Thanks