Current Location: Home> Latest Articles> PHP CSV Export Tutorial: Generating Standard CSV Files from Data

PHP CSV Export Tutorial: Generating Standard CSV Files from Data

gitbox 2025-08-08

Creating CSV Files from PHP Data

In PHP development, handling and exporting data is a common requirement. CSV (Comma-Separated Values) files are a popular format for exporting data due to their simplicity and compatibility across different applications. This article introduces how to use PHP to create CSV files from data, making data exchange and analysis more convenient.

What is a CSV File

A CSV file is a text file format where each line represents a record and fields are separated by commas. Its simple structure makes it easy to read and parse. CSV files are widely used for exporting data from databases, backing up data, and importing/exporting data in spreadsheet software.

Steps to Create CSV Files Using PHP

The main process to export CSV files is as follows:

Prepare data, usually as an array or data fetched from a database.

Open or create a CSV file using fopen().

Use PHP’s built-in fputcsv() function to write data line by line into the file, which automatically handles field delimiters and escaping.

After writing, close the file handle.

Example Code

The following example shows how to export a data array of student names and scores to a CSV file:

// Data array
$data = array(
    array('John Doe', 85),
    array('Jane Smith', 92),
    array('David Johnson', 78),
    array('Sarah Williams', 89)
);
// Open file handle
$file = fopen('students.csv', 'w');
// Write header row
fputcsv($file, array('Name', 'Score'));
// Write data rows
foreach ($data as $row) {
    fputcsv($file, $row);
}
// Close file handle
fclose($file);

Code Explanation

In this example, we first define a two-dimensional array $data containing student names and scores. We open a file named students.csv in write mode using fopen(). Then, we write the header and data rows using fputcsv(), which formats each line correctly as CSV. Finally, we close the file handle with fclose() to complete the file writing.

Conclusion

This article introduced how to easily generate CSV files with PHP’s fputcsv() function, which suits various data export scenarios. Mastering this method helps developers efficiently share and analyze data across platforms.