CSV Exports of SQL queries

CSV (comma-separated values) is the most widely supported format for transferring tabular data. That’s why CSV Exports are very common in web applications.

This simple PHP class will help you get started with CSV export. The main goal is to create a simple way to export data from your website or web application into a CSV that can be downloaded by the user. Obviously, this is not for performing a full database backup. Instead, this classes is meant for when you obtain data from a database query and want to pass it on to the user.

The first of these classes takes the results of a MySQL query and outputs in CSV format. Moreover, the package also offers a separate class for exporting PostgreSQL query results to a CSV file.

This PHP Class offers the choice of sending the output to the browser or downloading the CSV export as a file. This makes it a very flexible tool when it comes to exporting query results. The name and extension of the dump file are defined by the user.


Example 1: Download a CSV Export

Example 2: CSV export raw display (useful for debugging purposes)

If you call the CSV dump function with empty filename and extension, the script sends the query result directly to the browser as raw text

Final remarks

When using this class, you are able to save you time, as it simplifies the task of exporting data from a MySQL query  to CSV file. Moreover, all you have to do is add it to your project, add it using a require line and call it as shown in the example.

I published this PHP class PHPClasses quite a long time ago. However, I still find it very useful. I thought it’d be a good idea to share it here in the hope you find it useful too.

Summary
CSV export of a MySQL or PostgreSQL query with a simple PHP class
Article Name
CSV export of a MySQL or PostgreSQL query with a simple PHP class
Description
CSV export is one of the most widely used format for dumping data. This class uses the results of a SQL query and returns it as a CSV file
Author
Publisher Name
Iván Melgrati
Publisher Logo