Read CSV File into Array Using fgetcsv in PHP
This article explains how to read a CSV file and convert its contents
into a PHP array using the native fgetcsv() function. You
will learn the step-by-step process of opening a file, parsing its rows
sequentially through a loop, and structuring the data into a clean,
readable PHP array, including how to handle header rows.
The Basic Method to Read CSV into an Array
The fgetcsv() function in PHP reads a line from an open
file pointer and parses it for CSV fields. To convert an entire CSV file
into an array, you need to combine fopen(),
fgetcsv(), and a while loop.
Here is the standard implementation:
<?php
// Path to the CSV file
$filename = 'data.csv';
// Array to store the CSV data
$dataArray = [];
// Open the file in read-only mode
if (($handle = fopen($filename, 'r')) !== false) {
// Read each line of the CSV file
while (($row = fgetcsv($handle, 1000, ',')) !== false) {
$dataArray[] = $row;
}
// Close the file pointer
fclose($handle);
}
// Output the resulting array
print_r($dataArray);
?>How this code works:
fopen($filename, 'r'): Opens the CSV file for reading.fgetcsv($handle, 1000, ','): Reads a single line. The second argument (1000) limits the line length for performance (0 means unlimited), and the third argument (,) specifies the delimiter.whileLoop: Loops through the file line-by-line until it reaches the end of the file (false).fclose($handle): Closes the file to free up system resources.
Mapping CSV Headers to Array Keys
In many cases, the first row of your CSV file contains column headers
(e.g., “Name”, “Email”, “Phone”). You can map these headers as keys for
each associative array row using PHP’s array_combine()
function.
Here is how to read a CSV file into an associative array:
<?php
$filename = 'users.csv';
$dataArray = [];
if (($handle = fopen($filename, 'r')) !== false) {
// Get the first row to use as keys/headers
$headers = fgetcsv($handle, 1000, ',');
if ($headers !== false) {
// Loop through the remaining rows
while (($row = fgetcsv($handle, 1000, ',')) !== false) {
// Combine headers with row values
$dataArray[] = array_combine($headers, $row);
}
}
fclose($handle);
}
print_r($dataArray);
?>Why use associative arrays?
If your input CSV looks like this:
Name,Email
John Doe,john@example.com
The resulting PHP array will be structured cleanly with recognizable keys:
Array
(
[0] => Array
(
[Name] => John Doe
[Email] => john@example.com
)
)