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.
<
Writing 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/