otzy/csv-converter

将源CSV文件保存到目标文件,并包含所需字段集

v1.0.1 2018-07-18 21:50 UTC

This package is not auto-updated.

Last update: 2024-09-23 07:33:04 UTC


README

转换CSV文件(或任何带有分隔符的纯文本文件)为具有不同字段集的文件。

功能

  • 源文件和目标文件可能包含或不包含标题行
  • 字段可以通过字段名或索引表示
  • 目标字段可以使用任意回调函数进行计算
  • 对源文件标题和数据行的简单有效性检查。CSV Converter会检查标题是否具有您期望的准确字段数和顺序。

安装

composer require otzy/csv-converter

CsvConverter类

要读取源CSV并写入目标CSV,该类使用league/csv Reader和Writer。因此,当您需要使用不同的编码、BOM、流过滤器等读取/写入时,您可以使用league/csv包的完整功能。

映射

要转换,您首先需要创建映射。

映射是一个关联数组,定义了源文件中哪些字段将保存到目标文件中。该数组的键是目标CSV的字段名,值是从源CSV对应的字段。

您可以使用回调代替字段名来对输入字段执行任何转换。

以下是一个简单的映射器示例

$mapping = [
    'field two' => 'two',
    'field one' => 'one',
    'concat' => function ($fields, $source_field_index) {
        return $fields[$source_field_index['one']] . $fields[$source_field_index['two']];
    },
]

上述映射器将输出3个字段到目标: "field two"、"field one"、"concat"

第三个字段将从源文件的字段一和字段二中连接而成。

CSVConverter使用示例

        $mapping = [
            'field two' => 'two',
            'field one' => 'one',
            'concat' => function ($fields, $source_field_index) {
                return $fields[$source_field_index['one']] . $fields[$source_field_index['two']];
            },
        ];

        // Create an instance of class and set mapping
        $converter = new CsvConverter();
        $converter->setMapping($mapping);

        // whether source CSV has a header line
        $converter->setSourceHasHeader(true);
        
        // whether we want the destination CSV to have header line
        $converter->setTargetHasHeader(true);
        
        // Call this method if you want to be sure that source file has specific fields
        $converter->setValidSourceHeader(['one', 'two', 'three']);
        
        $reader = Reader::createFromPath('source.csv');
        $reader->setDelimiter(';');
        $reader->setEscape('\\');
        $reader->setEnclosure('"');

        $writer = Writer::createFromPath('target.csv');

        $writer->setDelimiter(';');
        $writer->setEscape('\\');
        $writer->setEnclosure('"');
        
        $converter->convert($reader, $writer);
        
        // league/csv Writer does not close stream, the only way to do this is to unset the object
        unset($writer);

事件

转换发出3种类型的事件

  • BeforeConvert - 在读取源行之后和将其转换为目的地之前
  • AfterRowConverted - 转换行已输出到目的地流之后
  • Complete - 当一切都完成后

您可以使用事件例如用于日志记录或显示转换的进度。

BeforeConvert也可以用于过滤行。如果事件处理器返回false,则该行不会写入目标流。

可以使用以下函数设置事件处理器

public function onBeforeConvert($callback) public function onRowConverted($callback) public function onCompleted($callback)