-
Notifications
You must be signed in to change notification settings - Fork 142
Evaluation CSV
Mark edited this page Jul 14, 2014
·
6 revisions
I used to use FileLib::readCsv() - and FileLib::readCsvFromString. But that proofed to be difficult with custom settings and more complex CSV files. So I use this only for internal and small files.
In general it is better to use the more advanced PHP wrapper libs around it.
I evaluated:
- https://github.com/thephpleague/csv (very advanced)
- https://github.com/goodby/csv (also quite advanced)
- https://github.com/kzykhys/PHPCsvParser (looks good)
- https://github.com/ockam/php-csv (simple)
- https://github.com/swt83/php-csv (simple)
And went with the first one. I mainly liked the idea of filtering.
"require": {
"league/csv": "5.*"
}
Optional, to use my current fork:
"require": {
"league/csv": "dev-develop"
},
"repositories" : [{
"type" : "vcs",
"url" : "https://github.com/dereuromark/csv"
}
Simple example:
use League\Csv\Reader;
$Reader = new Reader('/path/to/file.csv');
$Reader->setDelimiter(';');
$result = $Reader
->setLimit(20) // We just want the first 20 results
->fetchAll();
Advanced example:
use League\Csv\Reader;
use League\Csv\Filter\TranscodeFilter;
stream_filter_register(TranscodeFilter::FILTER_NAME."*", "League\Csv\Filter\TranscodeFilter");
$Reader = new Reader('/path/to/file.csv'); // Must be a file string in this case
$Reader->setDelimiter(';');
$Reader->appendStreamFilter(TranscodeFilter::FILTER_NAME . "iso-8859-1:utf-8");
$Reader->appendStreamFilter('string.toupper');
$result = $Reader
->addFilter(function ($row, $index) {
return $index > 0; //we don't take into account the header
})
->addFilter(function ($row) {
return isset($row[1], $row[2], $row[3]); //we make sure the data are present
})
->addFilter(function ($row) {
return $row[2] === 'F'; //we are only interested in girl firstname
})
->setLimit(20) // We just want the first 20 results
->fetchAll();