jdefez/laravel-csv 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

jdefez/laravel-csv

Composer 安装命令:

composer require jdefez/laravel-csv

包简介

laravel facade to read/write csv file

README 文档

README

This package provides a Laravel Facade for writing/reading Csv files.

Installation

$ composer require jdefez/laravel-csv

Reading a Csv file

This utility class does not take hold of any data. It simply provides an iterator you can use to read your csv files.

Basic usage

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

  }
}

Reading the first row

By default the first row is skipped. If you need to read the first row use $reader->withHeadings() method.

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

Reader::keyByColumnName()

The rows will be returned under the form of an associative arrays with the camel cased columns names as keys.

// 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()

The rows will be casted to object using the kamel cased column names as properties.

// 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"
  //}

  // ...
}

Mapping data

If you need a more sophisticated way to map your file. You could use 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);
  }
}

Fixing enconding

For this feature to work, you need to provide a list of expected encodings. They will be used to detect the current line encoding and if it has to be fixed. By default the Reader uses: ['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();

Writing a Csv file

You can both work with SplFileObject or SplTempFileObject.

This gist demonstrates how you can use SplTempFileObject

Writing an entire collection of data

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

Writing line by line.

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

Mapping data

You can also map data when writing to the file with Writer::write(callable $callback) of 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')
]);

Todo:

Reader:

  • Adding the ability to setup headings names. It could be a convinient way to map data. Especialy if we want to key by columns names or cast rows to stdClass when there are no columns names at all.

Writer:

  • Writing to a given encoding

jdefez/laravel-csv 适用场景与选型建议

jdefez/laravel-csv 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.37k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2021 年 09 月 13 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「csv」 「laravel」 「writer」 「reader」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 jdefez/laravel-csv 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 jdefez/laravel-csv 我们能提供哪些服务?
定制开发 / 二次开发

基于 jdefez/laravel-csv 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 1.37k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 7
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 1
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2021-09-13