tpmanc / csvhelper
处理CSV文件的辅助类
1.1.1
2016-08-17 09:41 UTC
Requires
- php: >=5.4.0
Requires (Dev)
- phpunit/phpunit: ~5.3
This package is not auto-updated.
Last update: 2024-09-26 00:09:27 UTC
README
处理CSV文件的辅助类。
通过Composer安装
运行以下命令
$ composer require tpmanc/csvhelper "*"
或者添加
$ "tpmanc/csvhelper": "*"
到你的composer.json
文件的require部分。
文件读取
file.csv
Russia;Moscow;
France;Paris;
Great Gritain;London;
use tpmanc\csvhelper\CsvHelper; ... CsvHelper::open('files/file.csv')->parse(function($line) { echo $line[0] . ': ' . $line[1]; });
结果
Russia: Moscow
France: Paris
Great Gritain: London
自定义分隔符
file.csv
Russia|Moscow|
France|Paris|
Great Gritain|London|
use tpmanc\csvhelper\CsvHelper; ... CsvHelper::open('files/file.csv')->delimiter('|')->parse(function($line) { echo $line[0] . ': ' . $line[1]; });
结果
Russia: Moscow
France: Paris
Great Gritain: London
更改编码
use tpmanc\csvhelper\CsvHelper; ... CsvHelper::open('files/file.csv')->encode('cp1251', 'utf-8')->parse(function($line) { echo $line[0] . ': ' . $line[1]; });
偏移和限制
file.csv
Russia;Moscow;
France;Paris;
Great Gritain;London;
use tpmanc\csvhelper\CsvHelper; ... CsvHelper::open('files/file.csv')->offset(1)->limit(1)->parse(function($line) { echo $line[0] . ': ' . $line[1]; });
结果
France: Paris
使用父作用域中的变量
file.csv
Russia;Moscow;
France;Paris;
Great Gritain;London;
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];
结果
3
Russia
France
创建新文件
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');