The Easy Way To CSV In PHP


CSVs are always those things that we underestimate. Like yeah, I know how to get and write the data. No problem. But, it always takes a little longer than I want and that's before I run into any weird edge cases.

Well, The PHP League has us covered with another extraordinary package!

CSV data manipulation made easy in PHP. - CSV
Working with CSV can often be much more difficult than you expect, with different types of delimiter and complicated structures. This makes it easy to read and write almost anything.

AND... It's super easy to use!

// import the reader
use League\Csv\Reader;

// load the file
$reader = Reader::createFromPath($localFilePath);

// if you have a header, let it know
$reader->setHeaderOffset(0);

// get the rows
$records = $reader->getRecords();

getRecords returns a really nice iterable model with all your data. Loop through and there you go! It's that simple. And you don't have to worry about proper line endings, and encodings and all the other stuff you will likely run into when dealing with CSVs.

Get started by installing it in your app

composer require league/csv

And then head over to the documentation for extra details!