Master Reading CSV Files into PHP Arrays: 6 Proven Methods
This guide explains six practical techniques for loading CSV data into PHP arrays, covering the classic fgetcsv() approach, associative mapping with headers, using file() and str_getcsv(), handling custom delimiters, skipping empty lines, streaming large files, and a reusable csvToArray function.
Overview
CSV (Comma‑Separated Values) files are a lightweight, human‑readable way to exchange tabular data between applications, and PHP provides several straightforward ways to import them into arrays for further processing.
What is a CSV File?
A CSV file stores table data as plain text, with each line representing a record and columns separated by a delimiter (commonly a comma, but sometimes a semicolon, tab, or pipe).
id,name,email
1,John Doe,[email protected]
2,Jane Smith,[email protected]
3,Bob Lee,[email protected]The goal is to read this file in PHP and convert it into an array.
Method 1: Use fgetcsv() (Classic)
The built‑in fgetcsv() function reads one line at a time and parses it into an array, making it memory‑efficient for large files.
<?php
$csvFile = fopen("data.csv", "r");
$data = [];
while (($row = fgetcsv($csvFile)) !== false) {
$data[] = $row;
}
fclose($csvFile);
print_r($data);
?>Sample output:
Array
(
[0] => Array ( [0] => id [1] => name [2] => email )
[1] => Array ( [0] => 1 [1] => John Doe [2] => [email protected] )
[2] => Array ( [0] => 2 [1] => Jane Smith [2] => [email protected] )
[3] => Array ( [0] => 3 [1] => Bob Lee [2] => [email protected] )
)Method 2: Convert Rows to Associative Arrays
To avoid numeric keys, read the first row as headers and combine each subsequent row with those headers.
<?php
$csvFile = fopen("data.csv", "r");
$headers = fgetcsv($csvFile); // first line
$data = [];
while (($row = fgetcsv($csvFile)) !== false) {
$data[] = array_combine($headers, $row);
}
fclose($csvFile);
print_r($data);
?>Sample output:
Array
(
[0] => Array ( [id] => 1 [name] => John Doe [email] => [email protected] )
[1] => Array ( [id] => 2 [name] => Jane Smith [email] => [email protected] )
[2] => Array ( [id] => 3 [name] => Bob Lee [email] => [email protected] )
)Method 3: Use file() with str_getcsv()
This concise approach reads the entire file into a string array and parses each line.
<?php
$rows = array_map('str_getcsv', file('data.csv'));
print_r($rows);
?>It is simple but loads the whole file into memory, so it suits small‑to‑medium CSVs.
Method 4: Handle Custom Delimiters
When a CSV uses a delimiter other than a comma (e.g., semicolon, tab, or pipe), pass the desired delimiter to fgetcsv().
<?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() powerful for varied CSV formats.
Method 5: Skip Empty Lines and Trim Data
Real‑world CSVs often contain blank lines, extra spaces, or incomplete rows. The following snippet skips empty rows and trims whitespace.
<?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: Efficiently Read Large CSV Files
For very large files (hundreds of megabytes), avoid loading everything into memory; process each row as it is read.
<?php
$csvFile = fopen("bigfile.csv", "r");
while (($row = fgetcsv($csvFile)) !== false) {
// Example: insert into a database
// insertIntoDatabase($row);
}
fclose($csvFile);
?>This streaming approach ensures constant memory usage.
Reusable csvToArray Function
The function below encapsulates CSV loading with optional header handling and custom delimiters.
<?php
function 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;
}
// Usage example
print_r(csvToArray("data.csv"));
?>Conclusion
Reading CSV files into PHP arrays is straightforward, but the best method depends on the use case:
For most scenarios, use fgetcsv() to read line‑by‑line.
If you need associative arrays with column names, combine rows with array_combine().
For small files and concise code, use file() together with str_getcsv().
For very large files, process rows in a streaming fashion to keep memory usage low.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Open Source Tech Hub
Sharing cutting-edge internet technologies and practical AI resources.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
