Examples

PHP CSV Export

Exporting Data to CSV

PHP CSV export uses fputcsv() for data output.

Introduction to PHP CSV Export

Exporting data to a CSV (Comma-Separated Values) file is a common requirement in many web applications. PHP offers a simple way to achieve this using the fputcsv() function. This function allows you to format and write data to a CSV file efficiently. In this guide, we will explore how to use fputcsv() to export data in PHP.

Setting Up the Environment

Before you start exporting data to a CSV file, make sure you have a PHP environment set up. You can use a local server such as XAMPP, WAMP, or a cloud-based solution. Ensure that you have access to write files to the directory where your script will be executed.

Using fputcsv() for CSV Export

The fputcsv() function formats a line as CSV and writes it to an open file. Let's look at a basic example:

Explanation of the Code

In the code above, we first open a file named data.csv in write mode. We check if the file was opened successfully to handle any file handling errors. We then define an array, $data, which contains the data to be exported. Each sub-array represents a row in the CSV file.

Using a foreach loop, we iterate over each row of data and use fputcsv() to write the row to the file. Finally, we close the file using fclose() to ensure that all data is written and resources are freed.

Adding CSV Headers for Download

Sometimes, you might want to prompt the user to download the CSV file instead of saving it directly on the server. You can do this by setting appropriate headers before writing the file:

Conclusion

Exporting data to a CSV file in PHP is straightforward with the use of fputcsv(). Whether you choose to save the file on the server or prompt users to download it, fputcsv() provides a flexible and simple approach to CSV export. Experiment with different datasets and explore more advanced features like custom delimiters to enhance your CSV export capabilities.