Lesson 3 of 6
CSV Processing - Reading Large Files with SplFileObject
CSV is the most common data exchange format for spreadsheets, database exports, and bulk imports. PHP's fgetcsv handles edge cases (quoted fields with commas, multi-line fields) that string splitting cannot. For large files, SplFileObject with line-by-line reading is the memory-efficient approach.
CSV Import, Export & SPL File Operations
<?php
declare(strict_types=1);
// ── Reading CSV - fgetcsv (correct approach) ───────────────────
function importPostsCsv(string $path): array {
$handle = fopen($path, "rb") ?: throw new RuntimeException("Cannot open CSV: $path");
$posts = [];
$row = 0;
$headers = [];
while (($data = fgetcsv($handle, 4096, ",")) !== false) {
if ($row === 0) {
$headers = array_map("strtolower", array_map("trim", $data));
$row++;
continue;
}
if (count($data) !== count($headers)) {
error_log("CSV row $row has wrong column count - skipping.");
$row++;
continue;
}
$posts[] = array_combine($headers, $data);
$row++;
}
fclose($handle);
return $posts;
}
// ── SplFileObject - better OOP approach for large files ────────
function iterateLargeCsv(string $path): Generator {
$file = new SplFileObject($path, "rb");
$file->setFlags(
SplFileObject::READ_CSV |
SplFileObject::SKIP_EMPTY |
SplFileObject::READ_AHEAD
);
$file->setCsvControl(",", '"', "\");
$headers = null;
foreach ($file as $row) {
if ($headers === null) {
$headers = array_map("trim", $row);
continue;
}
if (count($row) !== count($headers)) continue;
yield array_combine($headers, array_map("trim", $row));
}
}
// Usage - memory efficient (only one row in RAM at a time)
foreach (iterateLargeCsv("/storage/exports/posts.csv") as $post) {
// Process one row at a time - handles 10M rows without OOM
echo $post["title"] . "
";
}
// ── Writing CSV ────────────────────────────────────────────────
function exportPostsToCsv(array $posts, string $path): void {
$handle = fopen($path, "wb") ?: throw new RuntimeException("Cannot write CSV.");
// BOM for Excel UTF-8 compatibility
fwrite($handle, "");
// Header row
fputcsv($handle, ["ID", "Title", "Author", "Status", "Published At"]);
foreach ($posts as $post) {
fputcsv($handle, [
$post["id"],
$post["title"],
$post["author_name"],
$post["status"],
$post["published_at"] ?? "",
]);
}
fclose($handle);
}
// ── CSV download in browser ────────────────────────────────────
function downloadCsv(array $posts): void {
$filename = "posts_export_" . date("Y-m-d") . ".csv";
header("Content-Type: text/csv; charset=UTF-8");
header("Content-Disposition: attachment; filename="$filename"");
header("Pragma: no-cache");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Expires: 0");
$handle = fopen("php://output", "wb");
fwrite($handle, "");
fputcsv($handle, ["ID", "Title", "Author", "Status"]);
foreach ($posts as $post) {
fputcsv($handle, [$post["id"], $post["title"], $post["author_name"], $post["status"]]);
}
fclose($handle);
exit;
}Quick Quiz
Tip
Tip
Practice CSV Processing Reading Large Files with SplFileObject in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for CSV Processing - Reading Large Files with SplFileObject
Practice Task
Note
Practice Task - (1) Write a working example of CSV Processing Reading Large Files with SplFileObject from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with CSV Processing Reading Large Files with SplFileObject is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready php code.
Finished this lesson?