I have data in a MySQL database. I am sending the user a URL to get their data out as a CSV file.
I have the e-mailing of the link, MySQL query, etc. covered.
How can I, when they click the link, have a pop-up to download a CVS with the record from MySQL?
I have all the information to get the record already. I just don't see how to have PHP create the CSV file and let them download a file with a .csv extension.
Here is an improved version of the function from php.net that @Andrew posted.
It is really easy to use and works great with MySQL(i)/PDO result sets.
Remember to
exit()
after calling this if you are done with the page.The thread is a little old, I know, but for future reference and for noobs as myself:
Everyone else here explain how to create the CSV, but miss a basic part of the question: how to link. In order to link to download of the CSV-file, you just link to the .php-file, which in turn responds as being a .csv-file. The PHP headers do that. This enables cool stuff, like adding variables to the querystring and customize the output:
my_csv_creator.php can work with the variables given in the querystring and for example use different or customized database queries, change the columns of the CSV, personalize the filename and so on, e.g.:
Put in the
$output
variable the CSV data and echo with the correct headersWriting your own CSV code is probably a waste of your time, just use a package such as league/csv - it deals with all the difficult stuff for you, the documentation is good and it's very stable / reliable:
http://csv.thephpleague.com/
You'll need to be using composer. If you don't know what composer is I highly recommend you have a look: https://getcomposer.org/
To have it send it as a CSV and have it give the file name, use header():
http://us2.php.net/header
As far as making the CSV itself, you would just loop through the result set, formatting the output and sending it, just like you would any other content.
First make data as a String with comma as the delimiter (separated with ","). Something like this