NYCPHP Meetup

NYPHP.org

[nycphp-talk] Downloading a CSV file

Jeff Siegel jsiegel1 at optonline.net
Tue Sep 7 23:04:36 EDT 2004


Here's some pseudo code to get you started. It should prompt the user 
with a dialog box to save the file. However, keep in mind that if you 
have really large datasets (40,000 rows+) this may not work...PHP may 
run into memory issues. (You might want to see how phpMyAdmin handles 
very large datasets.) However, keep in mind that if the csv file is 
going to go into Excel...Excel has problems with very large datasets. On 
a recent project I had to divide an export into two 40,000 row datasets 
to be able to pull it into Excel.

Jeff S.
-----------------

$query 	= "SELECT * FROM MYTABLE
$result = mysql_query($query,$dbLink);


//For the first row in the file to have column names
$csv_output = "\"ColumnHead1\",\"ColumnHead2\"\n";

//Here's the data
while($row=mysql_fetch_assoc($result)){
$csv_output .=
"\"{$row['column1']}\",\"{$row['column2']}\"\n";
}

Header("Content-type: text/csv\n",true);
Header("Content-Disposition: attachment; filename=myfilename.csv",true); 

Header("Pragma: no-cache",true);
Header("Expires: 0",true);
print $csv_output;
exit;	



Faber Fedor wrote:

> Hi all,
> 
> I'm building a webapp (a telemarketing tracking thingie) and I'm trying
> to figure out the best way to do the following:
> 
> I want my worker bee to click on a link and download a CSV file that she
> will then use in a mail-merge.  The only way I can think of doing it I
> don't like.  I'm sure there's a better, PHP Approved Way (TM).
> 
> The only way I can think of doing it is to send a query via PHP to MySQL and
> telling MySQL to dump the data to a textfile in the website directory via
> SELECT...INTO OUTFILE..., then have PHP redirect to that file, and then
> delete the file. I don't like that way.
> 
> The only other thing I can think of is to have PHP grab the
> dataset, format the data as CSV and then...what?  Display it in her
> browser and have her do a File->Save?  Not nice, IMO.
> 
> Any brilliant ideas?
> 




More information about the talk mailing list