I covered how to use PHP's fputcsv without writing to a file in yesterday's post and look at a practical example today: fetching data from MySQL using PDO and sending it to the browser as a CSV, using the fputcsv() function.
Example data
Example code
Substitute the [database name], [username] and [password] fields with the appropriate credentials and name for your database, and modify the database query to suit your use case. If you are using a different library than PDO, then obviously you'll need to change the database function calls to use that library instead.
The example code writes out a header line containing the column names, and then one line for each record.
If you prefer to write the data out to a file, remove the two header lines and change php://output to the filename.
I'll cover how to buffer it into memory instead (for e.g. attaching to an email without having to write it out to file) in a subsequent post.
Example output
Example output from the fruit table:
0 comments:
Post a Comment