ork/csv

A library to read and write CSV files.

2.0.0 2023-10-09 19:41 UTC

This package is auto-updated.

Last update: 2024-05-05 16:59:53 UTC


README

Ork CSV is a library for reading and writing CSV files.

Latest Version PHP License PHPStan Test Status Code Coverage

Installation

composer require ork/csv

Reader

Ork CSV provides a reader to parse delimited files into arrays. The reader is implemented as an iterator that yields the contents of one CSV line per iteration. If the file has a header line with column names, each yielded array will be associative, keyed by the names in the header. If the file does not have a header line with columns names, each yielded array will be indexed.

For example, a file with a header line:

ID,Name,Size
1,foo,large
2,bar,small
$csv = new \Ork\Csv\Reader('/path/to/file.csv');
foreach ($csv as $row) {
    print_r($row);
}
Array
(
    [ID] => 1
    [Name] => foo
    [Size] => large
)
Array
(
    [ID] => 2
    [Name] => bar
    [Size] => small
)

A file without a header line:

1,foo,large
2,bar,small
$csv = new \Ork\Csv\Reader(file: '/path/to/file.csv', hasHeader: false);
foreach ($csv as $row) {
    print_r($row);
}
Array
(
    [0] => 1
    [1] => foo
    [2] => large
)
Array
(
    [0] => 2
    [1] => bar
    [2] => small
)

Writer

Ork CSV provides a writer that will track columns and automatically generate an appropriate header line.

$csv = new \Ork\Csv\Writer('/path/to/file.csv');
$csv->write([
    'Id' => 1,
    'Name' => 'foo',
    'Size' => 'large',
]);
$csv->write([
    'Id' => 2,
    'Name' => 'bar',
    'Size' => 'small',
]);
Id,Name,Size
1,foo,large
2,bar,small

See the docs directory for full details.