Goodby CSVライブラリで列数が異なるファイルを取り込む

Goodby CSVライブラリで列数が異なるファイルを取り込む

PHPのCSV入出力のライブラリで、行ごとに列数が異なるファイルを入出力すると、エラーが表示されます。
Column size should be %u, but %u columns given

列数が異なるファイルを取り込む

6行目に記載されているように、unstrict()を呼び出すことで厳密な列数のチェックを無効化できます。
列数が異なるCSVは存在すべきではないですが、アップロードされる以上、チェックする必要があります。

$config = new LexerConfig();
$lexer = new Lexer($config);

$interpreter = new Interpreter();
// 厳密なチェックを無効にする
$interpreter->unstrict();

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

列数が異なるファイルを出力する

4行目に記載されているように、unstrict()を呼び出すことで厳密な引数のチェックを無効化できます。
ただ、CSVとして列数が異なる行がある状態というのは異常なので、無効にするべきではありません。
作り出す側であれば、異なる行を含まない仕様に変更すべきです。

$config = new ExporterConfig();
$exporter = new Exporter($config);
// 厳密なチェックを無効にする
$exporter->unstrict();

$exporter->export('php://output', array(
    array('1', 'alice', 'alice@example.com'),
    array('2', 'bob', 'bob@example.com'),
    array('3', 'carol', 'carol@example.com'),
));

列数が異なるファイルを例外として処理する

unstrictを実行していなければ、例外が投げられるのでtry-catchで処理します。

取り込みの場合

try {
    $lexer->parse('user.csv', $interpreter);
} catch (Goodby\CSV\Import\Standard\Exception\StrictViolationException $e) {
    // 例外処理
}

出力の場合

StrictViolationExceptionは、クラス名が取り込み時のExceptionと全く同じですが、namespaceが異なります。
それぞれ別のExceptionなので、注意して下さい。

try {
    $exporter->export('php://output', array(
        array('1', 'alice', 'alice@example.com'),
        array('2', 'bob', 'bob@example.com'),
        array('3', 'carol', 'carol@example.com'),
    ));
} catch (Goodby\CSV\Export\Standard\Exception\StrictViolationException $e) {
    // 例外処理
}

プログラミングカテゴリの最新記事