CSV 导入/导出库

1.4.2 2023-03-15 19:52 UTC

This package is auto-updated.

Last update: 2024-09-15 23:19:03 UTC


README

这是一个对 goodby-csv 的分支,增加了对 PHP 8.1 的支持。

什么是 "Goodby CSV"?

Goodby CSV 是一个高度内存效率高、灵活且可扩展的开源 CSV 导入/导出库。

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);

特性

1. 无内存管理

该库旨在低内存使用。它不会在内存中累积所有行。导入器逐行读取 CSV 文件并执行回调函数。

2. 支持多字节

该库支持多字节输入/输出:例如,SJIS-win、EUC-JP 和 UTF-8。

3. 针对企业的应用程序即可使用

Goodby CSV 已完全单元测试。该库稳定,适用于大型项目,如企业应用程序。

要求

  • PHP 7.2 或更高版本

安装

通过 composer 安装该软件包

composer require handcraftedinthealps/goodby-csv

文档

配置

导入配置

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.
;

导出配置

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
;

非严格行一致性模式

默认情况下,当 Goodby CSV 发现具有与其他列不同列数的行时,会抛出 StrictViolationException。如果您想导入此类 CSV,可以调用 Interpreter::unstrict() 来在导入时禁用行一致性检查。

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);

示例

通过 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);

从 TSV(制表符分隔值)导入到数组

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);

从数组导出

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'],
]);

通过 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));

使用 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);

在 Symfony2 动作中导出

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;
	}
}

许可协议

Csv 是开源软件,许可协议为 MIT 许可证 - 有关详细信息,请参阅 LICENSE 文件

贡献

我们在测试驱动开发下工作。

从 github 检出 master 源代码

hub clone goodby/csv

通过 composer 安装组件

# If you don't have composer.phar
./scripts/bundle-devtools.sh .

# If you have composer.phar
composer.phar install --dev

运行 phpunit

./vendor/bin/phpunit

致谢

致谢信息位于 composer.json 文件中。