Read and load a CSV file into an array in PHP


- How to Read and Load a CSV File Into an Array in PHP
- What Is a CSV File?
- Method 1: Using fgetcsv() (The Classic Approach)
- Method 2: Converting Rows Into Associative Arrays
- Method 3: Using file() with str_getcsv()
- Method 4: Handling Custom Delimiters
- Method 5: Skipping Empty Lines and Trimming Data
- Method 6: Reading Large CSV Files Efficiently
- Bonus: Converting CSV to a Multi-Dimensional Array Function
- Conclusion
How to Read and Load a CSV File Into an Array in PHP
CSV (Comma-Separated Values) files are one of the most common ways to exchange data between applications. They’re lightweight, human-readable, and easy to work with in PHP. Whether you’re importing data from Excel, processing bulk uploads, or building a reporting tool, knowing how to read CSV file into array in PHP is an essential skill.
In this guide, we’ll cover different approaches to load CSV file into array in PHP using built-in functions and custom logic. By the end, you’ll have a clear understanding of when to use each method and how to handle real-world scenarios like headers, delimiters, and large files.
What Is a CSV File?
A CSV file stores tabular data in plain text. Each row represents a record, and columns are separated by a delimiter (commonly a comma, but sometimes semicolons or tabs).
Example data.csv
:
id,name,email1,John Doe,[email protected]2,Jane Smith,[email protected]3,Bob Lee,[email protected]
Our goal is to read this file in PHP and turn it into an array for easy processing.
fgetcsv()
(The Classic Approach)
Method 1: Using The most common way to read CSV file into array in PHP is with the built-in fgetcsv()
function. This function reads one line of the file at a time and automatically parses it into an array.
<?php$csvFile = fopen("data.csv", "r");$data = []; while (($row = fgetcsv($csvFile)) !== false) { $data[] = $row;} fclose($csvFile); print_r($data);
Output:
Array( [0] => Array ( [0] => id [1] => name [2] => email ) [1] => Array ( [0] => 1 [1] => John Doe [2] => john@example.com ) [2] => Array ( [0] => 2 [1] => Jane Smith [2] => jane@example.com ) [3] => Array ( [0] => 3 [1] => Bob Lee [2] => bob@example.com ))
This method is memory-friendly because it reads line by line. It’s ideal for large CSV files.
Method 2: Converting Rows Into Associative Arrays
Often, you don’t want numeric keys ([0]
, [1]
, [2]
). Instead, you want the headers (id
, name
, email
) as array keys. Here’s how:
<?php$csvFile = fopen("data.csv", "r"); // First row as headers$headers = fgetcsv($csvFile);$data = []; while (($row = fgetcsv($csvFile)) !== false) { $data[] = array_combine($headers, $row);} fclose($csvFile); print_r($data);
Output:
Array( [0] => Array ( [id] => 1 [name] => John Doe [email] => john@example.com ) [1] => Array ( [id] => 2 [name] => Jane Smith [email] => jane@example.com ) [2] => Array ( [id] => 3 [name] => Bob Lee [email] => bob@example.com ))
This format is much easier to work with when accessing data by column names.
file()
with str_getcsv()
Method 3: Using Another way to PHP load CSV file into array is combining file()
with str_getcsv()
. This reads the entire file into an array of strings and then parses each line.
<?php$rows = array_map('str_getcsv', file('data.csv'));print_r($rows);
This approach is very compact but loads the entire file into memory at once. It works great for small-to-medium CSV files but should be avoided for very large datasets.
Method 4: Handling Custom Delimiters
Not all CSV files use commas. Sometimes they use semicolons (;
), tabs (\t
), or even pipes (|
).
You can tell fgetcsv()
what delimiter to expect:
<?php$csvFile = fopen("data_semicolon.csv", "r");$data = []; while (($row = fgetcsv($csvFile, 1000, ";")) !== false) { $data[] = $row;} fclose($csvFile); print_r($data);
This flexibility makes fgetcsv()
very powerful.
Method 5: Skipping Empty Lines and Trimming Data
Real-world CSV files are often messy. You might find blank lines, extra spaces, or incomplete rows. Here’s how to handle them:
<?php$csvFile = fopen("data.csv", "r");$data = []; while (($row = fgetcsv($csvFile)) !== false) { // Skip empty lines if (count($row) == 1 && $row[0] === null) { continue; } // Trim spaces $row = array_map('trim', $row); $data[] = $row;} fclose($csvFile);
Method 6: Reading Large CSV Files Efficiently
When dealing with huge files (hundreds of MBs), reading everything into an array at once can exhaust memory. Instead, process rows as you read them:
<?php$csvFile = fopen("bigfile.csv", "r"); // Process each row immediatelywhile (($row = fgetcsv($csvFile)) !== false) { // For example, insert into a database // insertIntoDatabase($row);} fclose($csvFile);
This way, you never hold the entire dataset in memory.
Bonus: Converting CSV to a Multi-Dimensional Array Function
Here’s a reusable function to read CSV file into array in PHP with options for headers and delimiters:
<?phpfunction csvToArray($filename, $delimiter = ",", $hasHeader = true) { if (!file_exists($filename) || !is_readable($filename)) { return false; } $data = []; if (($handle = fopen($filename, "r")) !== false) { $headers = $hasHeader ? fgetcsv($handle, 1000, $delimiter) : []; while (($row = fgetcsv($handle, 1000, $delimiter)) !== false) { if ($hasHeader) { $data[] = array_combine($headers, $row); } else { $data[] = $row; } } fclose($handle); } return $data;} // Usageprint_r(csvToArray("data.csv"));
Conclusion
Reading a CSV file into an array in PHP is straightforward, but the right approach depends on your use case:
- Use
fgetcsv()
for most scenarios (line-by-line reading). - Use
array_combine()
if you want associative arrays with headers. - Use
file()
withstr_getcsv()
for small files when you want concise code. - Use streaming (processing rows as they come) for very large files.
Stay Updated.
I'll you email you as soon as new, fresh content is published.
Latest Posts