jdefez/laravel-csv

laravel 门面,用于读写 CSV 文件

v0.5.1 2022-04-05 12:27 UTC

This package is auto-updated.

Last update: 2024-09-10 21:20:32 UTC


README

此包提供 Laravel Facade,用于读写 CSV 文件。

安装

$ composer require jdefez/laravel-csv

读取 CSV 文件

此实用类不保留任何数据。它只提供了一个迭代器,您可以使用它来读取您的 CSV 文件。

基本用法

use Jdefez\LaravelCsv\Facades\Csv;

$file = new SplFileObject('path-to-my-file.csv', 'r');

if ($file->isReadable()) {
  $reader = Csv::reader($file);

  foreach ($reader->read() as $row) {

    // returns an array with the row's values

  }
}

读取第一行

默认情况下,第一行会被跳过。如果您需要读取第一行,请使用 $reader->withHeadings() 方法。

$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->withHeadings();

Reader::keyByColumnName()

行将以关联数组的形式返回,其中驼峰式列名称作为键。

// Given a file
//
// lastname;firstname;date of birth
// Jacky;Terror;1875-02-12
// Julian;Nightmare;1815-11-11

$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->keyByColumnName()

foreach ($reader->read() as $row) {

  //array(
  //    "firstname" => "Jacky",
  //    "lastname" => "Terror",
  //    "date_of_birth" => "1875-02-12"
  //)

  //...

}

Reader::toObject()

行将使用驼峰式列名称作为属性转换为对象。

// Given a file
//
// lastname;firstname;birthdate
// Jacky;Terror;1875-02-12
// Julian;Nightmare;1815-11-11

$reader = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->toObject()

foreach ($reader->read() as $row) {

  //object(stdClass)#277 (2) {
  //    ["firstname"]=> string(4) "Jacky"
  //    ["lastname"]=> string(5) "Terror"
  //    ["date_of_birth"]=> string(13) "1875-02-12"
  //}

  // ...
}

数据映射

如果您需要更复杂的方式来映射文件,您可以使用 Reader::read(?callable $callback = null): Generator

$iterator = Csv::reader(new SplFileObject('path-to-my-file.csv', 'r'))
  ->toObject()
  ->read(fn ($item) => UserDataBuilder::make(
    $item->firstname,
    $item->lastname,
    $item->date_of_birth,
  );

foreach ($iterator as $userData) {
  if ($userData->isValid()) {
    User::create($userData);
  }
}

修复编码

为了使此功能生效,您需要提供预期编码的列表。它们将被用于检测当前行的编码,以及是否需要修复。默认情况下,Reader 使用:['ISO-8859-15', 'ISO-8859-1']

// Fixing encoding from ISO to UTF-8

$reader = $reader->setToEncoding('UTF-8')
    ->setSearchEncodings(['ISO-8859-15', 'ISO-8859-1'])
    ->toObject();

写入 CSV 文件

您可以使用 SplFileObjectSplTempFileObject

此 gist 展示了如何使用 SplTempFileObject

写入整个数据集

$collection = collect([
  ['Jacky', 'Terror', '1875-02-12'],
  ['Julian', 'Nightmare', '1815-11-11'],
  // ...
]);

Csv::writer()
  ->setFile(new SplFileObject('path-to-my-file.csv', 'w'))
  ->setColumns(['firstname', 'lastname', 'date of birth'])
  ->setData($collection)
  ->write();

逐行写入。

$collection = collect([
  ['firstname', 'lastname', 'date_of_birth'],
  ['Jacky', 'Terror', '1875-02-12'],
  ['Julian', 'Nightmare', '1815-11-11'],
  // ...
]);

$writer = Csv::writer()->setFile(new SplFileObject('path-to-my-file.csv', 'w'));

$collection->each(fn ($line) => $writer->put($line));

数据映射

您还可以在写入文件时使用 Writer::write(callable $callback)Writer::put(array|callable $row) 映射数据。

$models = Users::all();

$writer = Csv::writer(new SplFileObject('path-to-my-file.csv', 'w'));

$writer->setData($models)
  ->write(fn ($item) => [
    $item->firstname,
    $item->lastname,
    $item->birthday->format('Y-m-d')
  ]);

// Or iterate over the collection and append each line to the file.

$models->each(fn ($model) => $writer->put(fn () => [
    $model->firstname,
    $model->lastname,
    $model->birthday->format('Y-m-d')
]);

待办事项

Reader

  • 添加设置标题名称的能力。这可能是一个方便的数据映射方法,特别是在我们想要根据列名称进行键设置或在没有列名称时将行转换为 stdClass 时。

Writer

  • 以指定编码写入