2

I am trying to create a CSV file that can be downloaded by the user and not have the data permanently saved on the server.

I am using mySQL and PHP for this page. I get the data in the right format to show up ("echo") on the webpage but not able to get the file to generate/download...maybe I am missing something or looking in the wrong place but any help would be great!

I have been trying several script both my own and others I have found but the one I currently have is below:

$file = 'export';
$colresult = mysql_query("SHOW COLUMNS FROM ".$tbl_name.""); 

if (mysql_num_rows($colresult) > 0) {  
while ($row = mysql_fetch_assoc($colresult)){   
$csv_output .= $row['Field'].", ";   $i++;  } } $csv_output .= "\n";   

$csvresult = mysql_query($sql); 

while ($rowr = mysql_fetch_row($csvresult)) {  
for ($j=0;$j<$i;$j++) {   $csv_output .= $rowr[$j].", ";  
}  

$csv_output .= "\n"; }   
$filename = $file."_".date("Y-m-d_H-i",time()).".csv"; 
header("Content-type: application/csv"); 
header("Content-disposition: attachment;filename=".$filename.".csv"); 
readfile("../documents/csv/".$filename.".csv");

$fp = fopen($filename, 'w');
foreach($csvret as $csvret){
fputcsv($fp, $csvret);
}

print $csv_output; 
print $filename; 

Thanks!

3
  • you should consider what would happen if your data contains commas Commented Mar 19, 2013 at 16:50
  • That been cleaned on the table side. Mainly want to get the file to create and will troubleshoot from there. Commented Mar 19, 2013 at 17:49
  • Then you may find implode(',' $record); and implode(',', array_keys($record)); useful with mysql_fetch_assoc(); Commented Mar 20, 2013 at 9:15

1 Answer 1

2

You'll need to pass some headers to force the web browser to recognize the file as "downloadable":

<?php

header('Content-Description: File Transfer');
header("Content-Type: application/csv"); 
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Content-Transfer-Encoding: binary');
header('Connection: Keep-Alive');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));

readfile($filename);
exit;

Simply add that code in place of:

print $csv_output; 
print $filename; 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.