phillipsdata / csv
CSV 读取器和写入器
1.1.0
2016-03-04 19:48 UTC
Requires
- php: >=5.4
Requires (Dev)
- phpunit/phpunit: ~4.8
- satooshi/php-coveralls: ~1.0
- squizlabs/php_codesniffer: ~2.3
This package is auto-updated.
Last update: 2024-09-23 09:50:53 UTC
README
一个没有外部依赖的 CSV 读取器和写入器,允许即时格式化和过滤,并可以操作文件和流。
安装
composer require phillipsdata/csv
基本用法
读取 CSV
<?php use PhillipsData\Csv\Reader; // Set the input for the reader $reader = Reader::input(new SplFileObject('php://stdin')); $lines = []; // Fetch the result for each line read foreach ($reader->fetch() as $line) { $lines[] = $line; }
写入 CSV
<?php use PhillipsData\Csv\Writer; $writer = Writer::output(new SplFileObject('/path/to/file.csv')); $data = [ ['colA', 'colB'], ['A1', 'B1'], ['A2', 'B2'] ]; // Write all rows (works great with Iterators) $writer->write($data); // Or, write a single row at a time foreach ($data as $row) { $writer->writeRow($row); }
工厂
<?php use PhillipsData\Csv\Factory; // returns \PhillipsData\Csv\Writer $writer = Factory::writer('path/to/file', ',', '"', '\\'); // returns \PhillipsData\Csv\Reader $reader = Factory::reader('path/to/file', ',', '"', '\\');
格式化和过滤
格式化和过滤适用于读取和写入。
在迭代时格式化数据,只需指定格式回调函数。
// The formatter is called for each line parsed $reader->format(function ($line, $key, $iterator) { return [ 'first_name' => $line['First Name'], 'last_name' => $line['Last Name'], 'email' => strtolower($line['Email']), 'date' => date('c', strtotime($line['Date'])) ]; }); foreach ($reader->fetch() as $line) { // $line now contains 'first_name', 'last_name', 'email', and 'date'. }
在迭代时过滤数据,只需指定过滤回调函数。
// The formatter is called for each line parsed $reader->filter(function ($line, $key, $iterator) { return $line['Last Name'] === 'Smith'; }); foreach ($reader->fetch() as $line) { // $line only contains records where $line['Last Name'] === 'Smith' }