To extract data from a CSV document use League\Csv\Reader methods.
The fetch method fetches the next row from the Iterator result set.
public Reader::fetch(callable $callable = null): Iterator
The method takes an optional callable parameter to apply to each row of the resultset before returning. The callable signature is as follow:
function(array $row [, int $rowOffset [, Iterator $iterator]]): array
$row: the CSV current row as an array$rowOffset: the CSV current row offset$iterator: the current CSV iteratoruse League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$results = $reader->fetch();
foreach ($results as $row) {
//do something here
}
use League\Csv\Reader;
$func = function ($row) {
return array_map('strtoupper', $row);
};
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$results = $reader->fetch($func);
foreach ($results as $row) {
//each row member will be uppercased
}
fetchAll returns a sequential array of all rows.
public Reader::fetchAll(callable $callable = null): array
fetchAll behaves exactly like fetch with one difference:
fetchAll returns an array.fetchOne return one single row from the CSV data as an array.
public Reader::fetchOne($offset = 0): array
The required argument $offset represents the row index starting at 0. If no argument is given the method will return the first row from the CSV data.
use League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$data = $reader->fetchOne(3); ///accessing the 4th row (indexing starts at 0)
// will return something like this :
//
// ['john', 'doe', 'john.doe@example.com']
//
each applies a callable function on each CSV row.
public Reader::each(callable $callable): int
The method returns the number of successful iterations.
The callable signature is as follows:
function(array $row [, int $rowOffset [, Iterator $iterator]]): bool
$row: the CSV current row as an array$rowOffset: the CSV current row offset$iterator: the current CSV iteratorThe callable must return true to continue iterating over the CSV;
use League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
//count the numbers of rows in a CSV
$nbRows = $reader->each(function ($row) {
return true;
});
fetchAssoc returns an Iterator of all rows. The rows themselves are associative arrays where the keys are a one dimension array. This array must only contain unique string and/or scalar values.
public Reader::fetchAssoc(
mixed $offset_or_keys = 0,
callable $callable = null
): Iterator
This $offset_or_keys argument can be
use League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$keys = ['firstname', 'lastname', 'email'];
$results = $reader->fetchAssoc($keys);
// $results is an iterator
foreach ($results as $row) {
// each row will have the following data
// [
// 'firstname' => 'john',
// 'lastname' => 'doe',
// 'email' => 'john.doe@example.com',
// ];
//
}
$offset = 0;
$results = $reader->fetchAssoc($offset);
// $results is an iterator
foreach ($results as $row) {
// each row will have the following data
// [
// 'john' => 'jane',
// 'doe' => 'doe',
// 'john.doe@example.com' => 'jane.doe@example.com',
// ];
//
}
null values to compensate for the missing values.The method takes an optional callable which signature is as follow:
function(array $row [, int $rowOffset [, Iterator $iterator]]): array
$row: the CSV current row combined with the submitted indexes (new in version 8.0.0)$rowOffset: the CSV current row offset$iterator: the current CSV iteratoruse League\Csv\Reader;
$func = function ($row) {
$row['date'] = DateTimeImmutable::createFromFormat($row['date'], 'd-m-Y');
return $row;
};
$keys = ['firstname', 'lastname', 'date'];
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
foreach ($reader->fetchAssoc($keys, $func) as $row) {
$row['date']->format('Y-m-d H:i:s');
//because this cell contain a `DateTimeInterface` object
}
fetchColumn returns a Iterator of all values in a given column from the CSV data.
public Reader::fetchColumn(
int $columnIndex = 0,
callable $callable = null
): Iterator
If for a given row the column does not exist, the row will be skipped.
use League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
$result = $reader->fetchColumn(2);
$data = iterator_to_array($result, false);
// will return something like this :
//
// ['john.doe@example.com', 'jane.doe@example.com', ...]
//
The method takes an optional callable which signature is as follow:
function(string $value [, int $offsetIndex [, Iterator $iterator]]): mixed
$value: the CSV current column value (new to version 8.0.0)$offsetIndex: the CSV current row offset$iterator: the current CSV iteratoruse League\Csv\Reader;
$reader = Reader::createFromPath('/path/to/my/file.csv', 'r');
foreach ($reader->fetchColumn(2, 'strtoupper') as $value) {
echo $value; //display 'JOHN.DOE@EXAMPLE.COM'
}
The fetchPairs method returns a Generator of key-value pairs.
public Reader::fetchPairs(
int $offsetIndex = 0,
int $valueIndex = 1,
callable $callable = null
): Generator
$offsetIndex).$valueIndex).use League\Csv\Reader;
$str = <<<EOF
john,doe
jane,doe
foo,bar
EOF;
$reader = Reader::createFromString($str);
foreach ($reader->fetchPairs() as $firstname => $lastname) {
// - first iteration
// echo $firstname; -> 'john'
// echo $lastname; -> 'doe'
// - second iteration
// echo $firstname; -> 'jane'
// echo $lastname; -> 'doe'
// - third iteration
// echo $firstname; -> 'foo'
// echo $lastname; -> 'bar'
}
$offsetIndex is provided it defaults to 0;$valueIndex is provided it defaults to 1;$offsetIndex the row is skipped;$valueIndex the null value is used;The method takes an optional callable which signature is as follow:
function(array $pairs [, int $rowOffset [, Iterator $iterator]]): array
$pairs: an array where
$rowOffset: the CSV current row offset$iterator: the current CSV iteratoruse League\Csv\Reader;
$str = <<<EOF
john,doe
jane,doe
foo,bar
EOF;
$func = function ($row) {
return [
strtoupper($row[0]),
strtolower($row[1]),
];
}
$reader = Reader::createFromString($str);
foreach ($reader->fetchPairs(1, 0, $func) as $lastname => $firstname) {
// - first iteration
// echo $lastname; -> 'DOE'
// echo $firstname; -> 'john'
// - second iteration
// echo $lastname; -> 'DOE'
// echo $firstname; -> 'jane'
// - third iteration
// echo $lastname; -> 'BAR'
// echo $firstname; -> 'foo'
}
The fetchPairsWithoutDuplicates method returns data in an array of key-value pairs, as an associative array with a single entry per row.
public Reader::fetchPairsWithoutDuplicates(
int $offsetIndex = 0,
int $valueIndex = 1,
callable $callable = null
): array
fetchPairsWithoutDuplicates behaves exactly like fetchPairs with two differences:
fetchPairsWithoutDuplicates returns an arrayfetchPairsWithoutDuplicates entries in the associative array will be overwritten if there are duplicates values in the column index.$str = <<<EOF
john,doe
jane,doe
foo,bar
EOF;
$reader = Reader::createFromString($str);
$data = $reader->fetchPairsWithoutDuplicates(1, 0);
// will return ['doe' => 'jane', 'foo' => 'bar'];
// the 'john' value has been overwritten by 'jane'
How can I help you explore Laravel packages today?