handcraftedinthealps/goodby-csv
Composer 安装命令:
composer require handcraftedinthealps/goodby-csv
包简介
CSV import/export library
README 文档
README
This is a fork of goodby-csv to add support for PHP 8.1.
What is "Goodby CSV"?
Goodby CSV is a highly memory efficient, flexible and extendable open-source CSV import/export library.
use Goodby\CSV\Import\Standard\Lexer; use Goodby\CSV\Import\Standard\Interpreter; use Goodby\CSV\Import\Standard\LexerConfig; $lexer = new Lexer(new LexerConfig()); $interpreter = new Interpreter(); $interpreter->addObserver(function(array $row) { // do something here. // for example, insert $row to database. }); $lexer->parse('data.csv', $interpreter);
Features
1. Memory Management Free
This library was designed for low memory usage. It will not accumulate all the rows in the memory. The importer reads a CSV file and executes a callback function line by line.
2. Multibyte support
This library supports mulitbyte input/output: for example, SJIS-win, EUC-JP and UTF-8.
3. Ready to Use for Enterprise Applications
Goodby CSV is fully unit-tested. The library is stable and ready to be used in large projects like enterprise applications.
Requirements
- PHP 7.2 or later
Installation
Install the package via composer:
composer require handcraftedinthealps/goodby-csv
Documentation
Configuration
Import configuration:
use Goodby\CSV\Import\Standard\LexerConfig; $config = new LexerConfig(); $config ->setDelimiter("\t") // Customize delimiter. Default value is comma(,) ->setEnclosure("'") // Customize enclosure. Default value is double quotation(") ->setEscape("\\") // Customize escape character. Default value is backslash(\) ->setToCharset('UTF-8') // Customize target encoding. Default value is null, no converting. ->setFromCharset('SJIS-win') // Customize CSV file encoding. Default value is null. ;
Export configuration:
use Goodby\CSV\Export\Standard\ExporterConfig; $config = new ExporterConfig(); $config ->setDelimiter("\t") // Customize delimiter. Default value is comma(,) ->setEnclosure("'") // Customize enclosure. Default value is double quotation(") ->setEscape("\\") // Customize escape character. Default value is backslash(\) ->setToCharset('SJIS-win') // Customize file encoding. Default value is null, no converting. ->setFromCharset('UTF-8') // Customize source encoding. Default value is null. ->setFileMode(CsvFileObject::FILE_MODE_WRITE) // Customize file mode and choose either write or append. Default value is write ('w'). See fopen() php docs ;
Unstrict Row Consistency Mode
By default, Goodby CSV throws StrictViolationException when it finds a row with a different column count to other columns. In the case you want to import such a CSV, you can call Interpreter::unstrict() to disable row consistency check at import.
rough.csv:
foo,bar,baz foo,bar foo foo,bar,baz
use Goodby\CSV\Import\Standard\Interpreter; use Goodby\CSV\Import\Standard\Lexer; use Goodby\CSV\Import\Standard\LexerConfig; $interpreter = new Interpreter(); $interpreter->unstrict(); // Ignore row column count consistency $lexer = new Lexer(new LexerConfig()); $lexer->parse('rough.csv', $interpreter);
Examples
Import to Database via PDO
user.csv:
1,alice,alice@example.com 2,bob,bob@example.com 3,carol,carol@eample.com
use Goodby\CSV\Import\Standard\Lexer; use Goodby\CSV\Import\Standard\Interpreter; use Goodby\CSV\Import\Standard\LexerConfig; $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root'); $pdo->query('CREATE TABLE IF NOT EXISTS user (id INT, `name` VARCHAR(255), email VARCHAR(255))'); $config = new LexerConfig(); $lexer = new Lexer($config); $interpreter = new Interpreter(); $interpreter->addObserver(function(array $columns) use ($pdo) { $stmt = $pdo->prepare('INSERT INTO user (id, name, email) VALUES (?, ?, ?)'); $stmt->execute($columns); }); $lexer->parse('user.csv', $interpreter);
Import from TSV (tab separated values) to array
temperature.tsv:
9 Tokyo 27 Singapore -5 Seoul 7 Shanghai
use Goodby\CSV\Import\Standard\Lexer; use Goodby\CSV\Import\Standard\Interpreter; use Goodby\CSV\Import\Standard\LexerConfig; $temperature = []; $config = new LexerConfig(); $config->setDelimiter("\t"); $lexer = new Lexer($config); $interpreter = new Interpreter(); $interpreter->addObserver(function(array $row) use (&$temperature) { $temperature[] = [ 'temperature' => $row[0], 'city' => $row[1], ]; }); $lexer->parse('temperature.tsv', $interpreter); print_r($temperature);
Export from array
use Goodby\CSV\Export\Standard\Exporter; use Goodby\CSV\Export\Standard\ExporterConfig; $config = new ExporterConfig(); $exporter = new Exporter($config); $exporter->export('php://output', [ ['1', 'alice', 'alice@example.com'], ['2', 'bob', 'bob@example.com'], ['3', 'carol', 'carol@example.com'], ]);
Export from database via PDO
use Goodby\CSV\Export\Standard\Exporter; use Goodby\CSV\Export\Standard\ExporterConfig; use Goodby\CSV\Export\Standard\CsvFileObject; use Goodby\CSV\Export\Standard\Collection\PdoCollection; $pdo = new PDO('mysql:host=localhost;dbname=test', 'root', 'root'); $pdo->query('CREATE TABLE IF NOT EXISTS user (id INT, `name` VARCHAR(255), email VARCHAR(255))'); $pdo->query("INSERT INTO user VALUES(1, 'alice', 'alice@example.com')"); $pdo->query("INSERT INTO user VALUES(2, 'bob', 'bob@example.com')"); $pdo->query("INSERT INTO user VALUES(3, 'carol', 'carol@example.com')"); $config = new ExporterConfig(); $exporter = new Exporter($config); $stmt = $pdo->prepare("SELECT * FROM user"); $stmt->execute(); $exporter->export('php://output', new PdoCollection($stmt));
Export with CallbackCollection
use Goodby\CSV\Export\Standard\Exporter; use Goodby\CSV\Export\Standard\ExporterConfig; use Goodby\CSV\Export\Standard\Collection\CallbackCollection; $data = []; $data[] = ['user', 'name1']; $data[] = ['user', 'name2']; $data[] = ['user', 'name3']; $collection = new CallbackCollection($data, function($row) { // apply custom format to the row $row[1] = $row[1] . '!'; return $row; }); $config = new ExporterConfig(); $exporter = new Exporter($config); $exporter->export('php://stdout', $collection);
Export in Symfony2 action
namespace AcmeBundle\ExampleBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\StreamedResponse; class DefaultController extends Controller { public function csvExportAction() { $conn = $this->get('database_connection'); $stmt = $conn->prepare('SELECT * FROM somewhere'); $stmt->execute(); $response = new StreamedResponse(); $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/csv'); $response->setCallback(function() use($stmt) { $config = new ExporterConfig(); $exporter = new Exporter($config); $exporter->export('php://output', new PdoCollection($stmt->getIterator())); }); $response->send(); return $response; } }
License
Csv is open-sourced software licensed under the MIT License - see the LICENSE file for details
Contributing
We works under test driven development.
Checkout master source code from github:
hub clone goodby/csv
Install components via composer:
# If you don't have composer.phar
./scripts/bundle-devtools.sh .
# If you have composer.phar
composer.phar install --dev
Run phpunit:
./vendor/bin/phpunit
Acknowledgement
Credits are found within composer.json file.
handcraftedinthealps/goodby-csv 适用场景与选型建议
handcraftedinthealps/goodby-csv 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.72M 次下载、GitHub Stars 达 44, 最近一次更新时间为 2021 年 11 月 26 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「csv」 「import」 「export」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 handcraftedinthealps/goodby-csv 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 handcraftedinthealps/goodby-csv 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 handcraftedinthealps/goodby-csv 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Bulk export of sylius resources
Parse use statements for a reflection object
Tool for copying data from a production database to a dev database. Also useful for making backups of production databases.
A fork of konnco/filament-import with support of Laravel 11 since the default importer of Filament 3 is nonsense for basic use case.
Yii2 export extension
laravel facade to read/write csv file
统计信息
- 总下载量: 1.72M
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 44
- 点击次数: 5
- 依赖项目数: 3
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-11-26