← Back to blog

Parsing CSV in PHP, the easiest way

| PHP

This article was published over 2 years ago. Some information may be outdated.

Do not use composer libraries for simple problems that pure PHP can solve.

For example, consider this code:

$csv = Reader::createFromPath(storage_path('dummy.csv'), 'r');
$csv->setHeaderOffset(0);

$records = $csv->getRecords();

foreach ($records as $record) {
    echo $record['first_name'];
}

This code extracts the first_name from a CSV file. It requires the league/csv composer package.

league/csv is one of the best CSV packages for PHP and provides convenient methods to work with CSV. But it is not solving a complex problem here -- it adds unnecessary complexity to the project.

If the problem is as simple as iterating over a CSV file, use PHP's built-in CSV functions instead.

Here is the same logic in pure PHP:

$csv = new SplFileObject(storage_path('dummy.csv'));
$csv->setFlags(SplFileObject::READ_CSV);
foreach ($csv as $item) {
    echo $item['first_name'];
}

Simpler, cleaner, and no extra packages.

You can use the setCsvControl method to specify additional options such as the delimiter.

Summary

  • Avoid unnecessary packages -- do not reach for a composer library when PHP's built-in functions handle the job.
  • SplFileObject -- PHP's native class for reading CSV files with READ_CSV flag, no external dependencies needed.
  • setCsvControl -- use this method to customize the delimiter and other CSV parsing options.
Share