One of the most common task you encounter as a developer is parsing data from CSV files. Though PHP has already a built in function to read the CSV file data however, accessing each column for each row can be confusing and time consuming if you code it from scratch.
Basically, the fgetcsv turns each row as an array of columns in which you can access the columns values by keys. Somehow as a CSV file becomes bigger and complex, remembering the keys and columns to access the field values can be a pain in the ass for a not so good developer just like me.
I decided to write a simple and straight forward library to provide and easy and convenient way to parse your CSV files. With just 1 line of code, you can easily parse a CSV file then access its data. Pretty convenient right?
Without further ado, here is my very simple and cool library.
Download via Composer
composer require jamesgordo/php-csv-parser
Or simply add this to your composer.json
{
"require": {
"jamesgordo/php-csv-parser": "1.0.0"
}
}
Don’t forget to run
composer update
Create a simple CSV file
users.csv
id,first_name,last_name
1,John,Doe
2,Eric,Smith
3,Mark,Cooper
Now create your parser.php
<?php
// load vendor autoload
require_once __DIR__ . '/vendor/autoload.php';
use JamesGordo\CSV\Parser;
// Initalize the Parser
$users = new Parser('/path/to/users.csv');
// loop through each user and echo the details
foreach($users->all() as $user) {
echo "User Details: {$user->id} | {$user->first_name} {$user->last_name}";
}
echo "Total Parsed: " . $users->count() . " Users";
The code above will output the following
User Details: 1 | John Doe
User Details: 2 | Eric Smith
User Details: 3 | Mark Cooper
Total Parsed: 3 Users
Once the library is initialized, you can just easily call $users->all() to get all the rows from the CSV file.
By setting the column name on the first row of your CSV file, you can easily call it directly as object properties:
- $user->id
- $user->first_name
- $user->last_name
With this, you can save up plenty of time and switch your focus more on functionalities you are developing.
Visit or fork the PHP CSV Parser repository on Github for more details.