CSV (Comma-Separated Values) files are commonly used to store and exchange tabular data.
CSV files are simple to read and write, making them an ideal choice for storing structured data in a plain text format.
PHP provides built-in functions for reading from and writing to CSV files, making it easy to work with CSV data in web applications.
In this tutorial, we will cover:
Table of Contents
Let’s dive into each of these concepts with examples and explanations.
1. What is a CSV File?
A CSV file is a plain text file that contains tabular data where each line represents a row, and each value within a line is separated by a comma (or another delimiter).
CSV files are widely used for storing and transferring data because of their simplicity and compatibility with various systems, including databases, spreadsheets, and text editors.
Example CSV File (data.csv):
Name,Age,Email John Doe,25,john@example.com Jane Smith,30,jane@example.com Mark Johnson,22,mark@example.com
- This CSV file contains three rows of data with headers (Name, Age, Email).
2. Reading a CSV File Using fgetcsv()
The fgetcsv() function reads a line from an open file and parses it into an array, where each element corresponds to a field in the CSV file. This function is ideal for reading CSV files line by line.
Syntax:
fgetcsv(file_handle, length, delimiter);
- file_handle: The handle of the file opened with fopen().
- length: Optional. The number of bytes to read. If omitted, it will read the entire line.
- delimiter: Optional. The delimiter that separates fields (default is a comma ,).
Example (Reading a CSV File Line by Line):
<?php $file = fopen("data.csv", "r"); // Open the CSV file for reading if ($file) { // Read and output each row of the CSV file while (($row = fgetcsv($file)) !== false) { echo "Name: " . $row[0] . ", Age: " . $row[1] . ", Email: " . $row[2] . "\n"; } fclose($file); // Close the file after reading } else { echo "Error: Could not open the file.\n"; } ?>
Output:
Name: John Doe, Age: 25, Email: john@example.com Name: Jane Smith, Age: 30, Email: jane@example.com Name: Mark Johnson, Age: 22, Email: mark@example.com
- In this example, fgetcsv() reads the CSV file row by row and parses each row into an array.
3. Writing to a CSV File Using fputcsv()
The fputcsv() function writes an array of data to a CSV file, converting each element of the array into a field in the CSV row.
Syntax:
fputcsv(file_handle, fields, delimiter);
- file_handle: The handle of the file opened with fopen().
- fields: The array of data to write as a CSV row.
- delimiter: Optional. The delimiter to use between fields (default is a comma ,).
Example (Writing Data to a CSV File):
<?php $data = [ ["Name", "Age", "Email"], ["John Doe", 25, "john@example.com"], ["Jane Smith", 30, "jane@example.com"], ["Mark Johnson", 22, "mark@example.com"] ]; $file = fopen("output.csv", "w"); // Open the file for writing if ($file) { foreach ($data as $row) { fputcsv($file, $row); // Write each row to the CSV file } fclose($file); // Close the file echo "Data successfully written to output.csv\n"; } else { echo "Error: Could not open the file for writing.\n"; } ?>
- In this example, fputcsv() writes an array of data to output.csv, creating a CSV file with headers and rows.
Output in output.csv:
Name,Age,Email John Doe,25,john@example.com Jane Smith,30,jane@example.com Mark Johnson,22,mark@example.com
4. Reading a CSV File into an Array
To load an entire CSV file into an array, you can loop through each row using fgetcsv() and append each row to an array. This allows you to process the entire CSV file in memory.
Example (Loading a CSV File into an Array):
<?php $rows = []; $file = fopen("data.csv", "r"); if ($file) { while (($row = fgetcsv($file)) !== false) { $rows[] = $row; // Append each row to the array } fclose($file); // Close the file // Output the array for demonstration print_r($rows); } else { echo "Error: Could not open the file.\n"; } ?>
Output:
Array ( [0] => Array ( [0] => Name [1] => Age [2] => Email ) [1] => Array ( [0] => John Doe [1] => 25 [2] => john@example.com ) [2] => Array ( [0] => Jane Smith [1] => 30 [2] => jane@example.com ) [3] => Array ( [0] => Mark Johnson [1] => 22 [2] => mark@example.com ) )
- In this example, the CSV file is loaded into an array, with each row stored as an array within the $rows array.
5. Writing an Array to a CSV File
You can also write an array to a CSV file using fputcsv() by looping through the array and writing each row to the file.
Example (Writing an Array to a CSV File):
<?php $rows = [ ["Name", "Age", "Email"], ["John Doe", 25, "john@example.com"], ["Jane Smith", 30, "jane@example.com"], ["Mark Johnson", 22, "mark@example.com"] ]; $file = fopen("new_data.csv", "w"); // Open the file for writing if ($file) { foreach ($rows as $row) { fputcsv($file, $row); // Write each array row to the CSV file } fclose($file); // Close the file echo "Array data written to new_data.csv\n"; } else { echo "Error: Could not open the file for writing.\n"; } ?>
- In this example, an array is written to new_data.csv using fputcsv().
Output in new_data.csv:
Name,Age,Email John Doe,25,john@example.com Jane Smith,30,jane@example.com Mark Johnson,22,mark@example.com
6. Handling CSV Files with Headers
Often, CSV files contain headers as the first row. When reading such files, you may want to treat the first row differently (e.g., storing it as column names).
Example (Reading a CSV File with Headers):
<?php $headers = []; $rows = []; $file = fopen("data.csv", "r"); if ($file) { $headers = fgetcsv($file); // Read the first row as headers // Read the remaining rows while (($row = fgetcsv($file)) !== false) { $rows[] = array_combine($headers, $row); // Combine headers with row values } fclose($file); // Output the associative array print_r($rows); } else { echo "Error: Could not open the file.\n"; } ?>
Output:
Array ( [0] => Array ( [Name] => John Doe [Age] => 25 [Email] => john@example.com ) [1] => Array ( [Name] => Jane Smith [Age] => 30 [Email] => jane@example.com ) [2] => Array ( [Name] => Mark Johnson [Age] => 22 [Email] => mark@example.com ) )
- In this example, the first row is treated as headers, and the subsequent rows are combined with the headers to create associative arrays.
7. Use Case: Exporting and Importing Data Using CSV Files
Use Case: Exporting and Importing Data Using CSV Files**
Let’s consider a simple use case where you need to export user data to a CSV file and later import it back into the system.
Exporting Data to CSV:
<?php $users = [ ["John Doe", 25, "john@example.com"], ["Jane Smith", 30, "jane@example.com"], ["Mark Johnson", 22, "mark@example.com"] ]; $file = fopen("users.csv", "w"); if ($file) { // Add headers fputcsv($file, ["Name", "Age", "Email"]); // Write user data foreach ($users as $user) { fputcsv($file, $user); } fclose($file); echo "User data exported to users.csv\n"; } else { echo "Error: Could not open the file.\n"; } ?>
Importing Data from CSV:
<?php $users = []; $file = fopen("users.csv", "r"); if ($file) { // Read headers $headers = fgetcsv($file); // Read user data while (($row = fgetcsv($file)) !== false) { $users[] = array_combine($headers, $row); // Combine headers with user data } fclose($file); // Output imported data print_r($users); } else { echo "Error: Could not open the file.\n"; } ?>
Summary of PHP CSV Functions:
Function | Description |
---|---|
fgetcsv() | Reads a line from a CSV file and parses it into an array. |
fputcsv() | Writes an array to a CSV file as a single row. |
file() | Reads an entire file into an array, one line per array element. |
fopen(), fclose() | Opens and closes files, required for reading/writing CSV files. |
Conclusion
CSV files are widely used for exchanging and storing structured data in PHP. In this tutorial, we explored:
- Reading a CSV file using fgetcsv() line by line.
- Writing data to a CSV file using fputcsv().
- Handling headers in CSV files.
- Loading a CSV file into an array and writing an array to a CSV file.
- Practical examples of exporting and importing data using CSV files.