PHP create csv and force download

Hi Guys,

I am trying to create a csv file and force the download in the users browser (should also be compatible with IE7). Does anyone know how this can be done?

I have created the following php script which creates a csv file then attempts to download it from the server. The file is created on the server and the content gets written to it. The download is also forced in the users browser, however, the only problem is that when the user saves or opens the file there is no data to be seen (blank file). Any ideas why this is happening? Am I missing something?

$FileName = date("d-m-y").'.csv';
				$NewFile = fopen($FULL_PATH_TO_DT.'/admin/downloads/excel/'.$FileName,"w+");
				if(fwrite($NewFile, $Content) === FALSE) {
					$Errors['error'][] = "Could not write to CSV file!";
				}
				fclose($NewFile);
				header("Content-type: application/force-download");
       			header('Content-Disposition: inline; filename="'.$NewFile.'"');
       			header("Content-Transfer-Encoding: Binary");
       			header("Content-length: ".filesize($NewFile));
       			header('Content-Type: application/excel');
       			header('Content-Disposition: attachment; filename="'.$FileName.'"');
       			readfile($NewFile);

Please help :frowning:

I am not sure how your $Content variable holds the csv data but the following piece of code works fine for me in FF2.0 and IE6.


$FileName = date("d-m-y") . '.csv';
$Content = "";

# Titlte of the CSV
$Content = "Name,Address,Age,Phone \
";

# fill data in the CSV
$Content .= "\\"John Doe\\",\\"New York, USA\\",15,65465464 \
";

header('Content-Type: application/csv'); 
header("Content-length: " . filesize($NewFile)); 
header('Content-Disposition: attachment; filename="' . $FileName . '"'); 
echo $Content;
exit();