What is the most efficient way to convert a MySQL query to CSV in PHP please?
It would be best to avoid temp files as this reduces portability (dir paths and setting file-system permissions required).
The CSV should also include one top line of field names.
Look at the documentation regarding the SELECT ... INTO OUTFILE syntax.
If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)
These functions setup the headers:
This one sends a CSV to a stream using a mysql result
This one uses the above function to write a CSV to a file, given by $filename
And this is where the magic happens ;)
For example:
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
Check out this question / answer. It's more concise than @Geoff's, and also uses the builtin fputcsv function.
An update to @jrgns (with some slight syntax differences) solution.