CSV Helper is a robust parser/builder for converting CSV data to arrays and vice versa. This tool is designed for handling large CSV datasets efficiently.
- Parse CSV files into arrays.
- Extract specific columns from CSV files.
- Iterate through CSV records seamlessly.
- Build CSV files from arrays.
The preferred method of installing this extension is through Composer.
You can install the package by running the following command:
composer require --prefer-dist buibr/csv-helper "^1.5"
Alternatively, you can add it directly to the require
section of your composer.json
file:
"require": {
"buibr/csv-helper": "*"
}
To parse a CSV file and get the data as an array:
<?php
use buibr\csvhelper\CsvParser;
$parser = new CsvParser('path/to/file');
$data = $parser->fromFile()->toArray();
?>
Alternatively, you can parse the CSV file and directly get the data as an array in a single line:
<?php
use buibr\csvhelper\CsvParser;
$data = (new CsvParser)->fromFile('path/to/file')->toArray();
?>
Consider the following file.csv
:
name,email,phone
aaa,bbb,ccc
ddd,eee,fff
ggg,hhh,iii
To extract the email
column:
<?php
use buibr\csvhelper\CsvParser;
$data = (new CsvParser)->fromFile('path/to/file')->toColumn('email');
?>
Result:
$data = [
0 => "bbb",
1 => "eee",
2 => "hhh"
];
To extract multiple columns:
<?php
use buibr\csvhelper\CsvParser;
$data = (new CsvParser('path/to/file'))->toColumns(['email', 'phone']);
?>
Result:
$data = [
0 => ["bbb", "ccc"],
1 => ["eee", "fff"],
2 => ["hhh", "iii"]
];
<?php
use buibr\csvhelper\CsvParser;
$csv = new CsvParser('path/to/file');
$first = $csv->current();
Result:
Array
(
[0] => John
[1] => Doe
[2] => [email protected]
[3] => 003344003203
[4] => Unknown
)
<?php
use buibr\csvhelper\CsvParser;
$assoc = $csv->current(true);
Result:
Array
(
[Firstname] => John
[Lastname] => Doe
[Email] => [email protected]
[Phone] => 003344003203
[Adress] => Unknown
)
<?php
use buibr\csvhelper\CsvParser;
$csv = new CsvParser('path/to/file');
while ($csv->valid()) {
// Get item as array
$item = $csv->current(true);
// Get the value of the 'Firstname' column from the current record
$name = $csv->column('Firstname');
// Get some of the columns
$fullname = implode(' ', $csv->columns(['Firstname', 'Lastname']));
$csv->next();
}
Explore the test
folder in this repository to see additional examples and use cases.
This README provides a detailed guide on installing and using the CSV Helper. If you encounter any issues or have questions, feel free to open an issue on the GitHub repository.