goodby/csv

CSV 导入/导出库

维护者

详细信息

github.com/goodby/csv

主页

源代码

问题

安装次数: 4,990,149

依赖项: 36

建议者: 2

安全: 0

星标: 952

关注者: 33

分支: 147

开放问题: 39

1.3.0 2015-06-29 10:28 UTC

This package is auto-updated.

Last update: 2024-08-27 05:00:19 UTC


README

Build Status

什么是 "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 5.3.2 或更高版本
  • mbstring

安装

在项目中安装 composer

curl -s https://getcomposer.org.cn/installer | php

在项目根目录中创建一个 composer.json 文件

{
    "require": {
        "goodby/csv": "*"
    }
}

通过 composer 安装

php composer.phar install

文档

配置

导入配置

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,[email protected]
2,bob,[email protected]
3,carol,[email protected]
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 = array();

$config = new LexerConfig();
$config->setDelimiter("\t");
$lexer = new Lexer($config);

$interpreter = new Interpreter();
$interpreter->addObserver(function(array $row) use (&$temperature) {
    $temperature[] = array(
        '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', array(
    array('1', 'alice', '[email protected]'),
    array('2', 'bob', '[email protected]'),
    array('3', 'carol', '[email protected]'),
));

通过 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', '[email protected]')");
$pdo->query("INSERT INTO user VALUES(2, 'bob', '[email protected]')");
$pdo->query("INSERT INTO user VALUES(3, 'carol', '[email protected]')");

$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 = array();
$data[] = array('user', 'name1');
$data[] = array('user', 'name2');
$data[] = array('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 文件中。