Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/tpmanc/csv-helper
Helper for csv files
https://github.com/tpmanc/csv-helper
csv csv-files php
Last synced: 27 days ago
JSON representation
Helper for csv files
- Host: GitHub
- URL: https://github.com/tpmanc/csv-helper
- Owner: tpmanc
- Created: 2015-10-06T12:57:42.000Z (over 9 years ago)
- Default Branch: master
- Last Pushed: 2016-11-30T14:08:48.000Z (about 8 years ago)
- Last Synced: 2024-09-14T21:49:13.258Z (4 months ago)
- Topics: csv, csv-files, php
- Language: PHP
- Size: 12.7 KB
- Stars: 0
- Watchers: 3
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# CSV Helper
Helper class for working with CSV files.## Install via Composer
Run the following command
```bash
$ composer require tpmanc/csvhelper "*"
```or add
```bash
$ "tpmanc/csvhelper": "*"
```to the require section of your `composer.json` file.
## File reading
file.csv:
```
Russia;Moscow;
France;Paris;
Great Gritain;London;
``````php
use tpmanc\csvhelper\CsvHelper;...
CsvHelper::open('files/file.csv')->parse(function($line) {
echo $line[0] . ': ' . $line[1];
});
```Result:
```
Russia: Moscow
France: Paris
Great Gritain: London
```### Custom delimiter
file.csv:
```
Russia|Moscow|
France|Paris|
Great Gritain|London|
``````php
use tpmanc\csvhelper\CsvHelper;...
CsvHelper::open('files/file.csv')->delimiter('|')->parse(function($line) {
echo $line[0] . ': ' . $line[1];
});
```Result:
```
Russia: Moscow
France: Paris
Great Gritain: London
```### Change encoding
```php
use tpmanc\csvhelper\CsvHelper;...
CsvHelper::open('files/file.csv')->encode('cp1251', 'utf-8')->parse(function($line) {
echo $line[0] . ': ' . $line[1];
});
```### Offset and limit
file.csv:
```
Russia;Moscow;
France;Paris;
Great Gritain;London;
``````php
use tpmanc\csvhelper\CsvHelper;...
CsvHelper::open('files/file.csv')->offset(1)->limit(1)->parse(function($line) {
echo $line[0] . ': ' . $line[1];
});
```Result:
```
France: Paris
```### Using variables from the parent scope
file.csv:
```
Russia;Moscow;
France;Paris;
Great Gritain;London;
``````php
use tpmanc\csvhelper\CsvHelper;...
$lineCount = 0;
$array = [];
CsvHelper::open('files/file.csv')->parse(function($line) use(&$lineCount, &$array) {
$lineCount++;
$array[] = $line[0];
});
echo $lineCount;
echo $array[0];
echo $array[1];
```Result:
```
3
Russia
France
```## Create new file
```php
use tpmanc\csvhelper\CsvHelper;...
$file = CsvHelper::create()->delimiter(';');
$file->encode('cp1251', 'utf-8'); // change encoding
$file->addLine('1.;France;'); // add row to file by string
$file->addLine([
2,
'Germany'
]); // add row to file by array$file->save('./new-file.csv');
```