Read and write CSV files with PHP.
This package provides a minimalistic wrapper around the excellent league/csv
package. The API is heavily inspired by Ruby's CSV
class.
Installation
You can install the package via Composer:
composer require ryangjchandler/csv
Usage
Looping over each row in a file
To loop over each row in a CSV file, you can use the Csv::foreach()
method.
use RyanChandler\Csv\Csv;
Csv::foreach('/path/to/file', do: function (array $record, int $offset): void {
});
The callback function provided will receive each row in the file as an array.
By default a header row will be read from the top of the file. If you wish to disable this behaviour you can provide a named boolean header
argument:
Csv::foreach('/path/to/file', do: function (array $record, int $offset): void {
}, header: false);
If the header for the file isn't on the first row, you can specify the row offset with the headerOffset
named argument:
Csv::foreach('/path/to/file', do: function (array $record, int $offset): void {
}, headerOffset: 10);
Reading an entire file
When working with small files it's likely easier to read the entire file into a single array. This can be done with the Csv::read()
method.
$records = Csv::read('/path/to/file');
This method accepts the same named arguments as Csv::foreach()
except $do
.
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.