[PHP] Read a CSV file

Created on November 30, 2026

Use SplFileObject to read and format rows from a CSV file. Save the following as sample.csv.

sato,11
suzuki,15
tanaka,20
yamada,33
<?php

$file = new SplFileObject('sample.csv');
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);

foreach($file as $line) {
    echo $line[0] . ': ' . $line[1] . PHP_EOL;
}

Pass the path to the constructor and combine the flags to parse CSV and skip empty lines. Use foreach to process one row at a time.

sato: 11
suzuki: 15
tanaka: 20
yamada: 33
PHP