How to Read CSV File in PHP: Simple Guide with Examples
To read a CSV file in PHP, use the
fopen function to open the file and fgetcsv to read each line as an array. Loop through the file until the end is reached, then close it with fclose.Syntax
The basic syntax to read a CSV file in PHP involves three main functions:
fopen(filename, mode): Opens the CSV file for reading.fgetcsv(file_handle): Reads one line from the file and parses it as CSV, returning an array of values.fclose(file_handle): Closes the file after reading is done.
This pattern lets you read each row of the CSV file as an array of strings.
php
<?php $file = fopen('file.csv', 'r'); while (($row = fgetcsv($file)) !== false) { // process $row array } fclose($file); ?>
Example
This example reads a CSV file named data.csv and prints each row as a list of values.
php
<?php $file = fopen('data.csv', 'r'); if ($file === false) { die('Error opening the file'); } while (($row = fgetcsv($file)) !== false) { echo 'Row data: ' . implode(', ', $row) . "\n"; } fclose($file); ?>
Output
Row data: John, Doe, 30
Row data: Jane, Smith, 25
Row data: Bob, Johnson, 40
Common Pitfalls
Common mistakes when reading CSV files in PHP include:
- Not checking if the file opened successfully before reading.
- Not handling empty lines or malformed CSV rows.
- Forgetting to close the file with
fclose, which can cause resource leaks. - Assuming all CSV files use commas; some use semicolons or tabs, so specify the delimiter in
fgetcsvif needed.
php
<?php // Wrong: Not checking if file opened $file = fopen('missing.csv', 'r'); if ($file !== false) { while (($row = fgetcsv($file)) !== false) { print_r($row); } fclose($file); } // Right: Check file open $file = fopen('missing.csv', 'r'); if ($file === false) { die('File not found'); } while (($row = fgetcsv($file)) !== false) { print_r($row); } fclose($file);
Quick Reference
Here is a quick summary of key functions and tips for reading CSV files in PHP:
| Function | Purpose | Notes |
|---|---|---|
| fopen(filename, 'r') | Open CSV file for reading | Returns file handle or false on failure |
| fgetcsv(file_handle, length = 0, delimiter = ',', enclosure = '"') | Read one CSV row as array | Specify delimiter if not comma |
| fclose(file_handle) | Close the opened file | Always close to free resources |
| Checking fopen result | Ensure file opened before reading | Avoid errors if file missing |
| Loop with fgetcsv | Read all rows until false | Use while loop for all lines |
Key Takeaways
Use fopen and fgetcsv together to read CSV files line by line as arrays.
Always check if fopen succeeded before reading the file.
Close the file with fclose to free system resources.
Specify the delimiter in fgetcsv if your CSV uses a separator other than a comma.
Handle empty or malformed lines gracefully to avoid errors.