wilgucki/csv 问题修复 & 功能扩展

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

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

wilgucki/csv

最新稳定版本:1.0

Composer 安装命令:

composer require wilgucki/csv

包简介

Laravel 5 package for writing and reading CSV files

关键字:

README 文档

README

Laravel 5 package for reading and writing CSV files.

Warning

The package has been updated to PHP 7. If you can't update to PHP 7 use version 0.6.x

Instalation

Install package with composer

composer require wilgucki/csv

For projects built with Laravel 5.5+ you can ommit next step. Package uses package discovery feature so you don't need to modify config file. For older Laravel versions you will need to add service provider and aliases to config/app.php file

'providers' => [
    //... 
    Wilgucki\Csv\CsvServiceProvider::class,
]

// ...

'aliases' => [
    //...
    'CsvReader' => Wilgucki\Csv\Facades\Reader::class,
    'CsvWriter' => Wilgucki\Csv\Facades\Writer::class,
]

Last step is to publish package config

php artisan vendor:publish --provider="Wilgucki\Csv\CsvServiceProvider"

Usage

Config file

Package config can be found in csv.php file under config directory (after you have published it). The file contains default values for delimiter, enclosure and escape parameters. You can set default values here and skip passing additional parameters to open and create methods (we discuss them later).

Convert encoding

Common issue when working with CSV files generated by Excel is encoding. Excel exports CSV file encoded with windows-1250 character set while most of PHP applications use UTF-8. To solve this issue you can set encoding option in the config file. You can set your encoding preferences separately for reader and writer.

'encoding' => [
    'reader' => [
        'enabled' => true,
        'from' => 'CP1250',
        'to' => 'UTF-8'
    ],
    'writer' => [
        'enabled' => true,
        'from' => 'UTF-8',
        'to' => 'CP1250'
    ]
]

As you can see in the example above, Reader will convert windows-1250 encoding to UTF-8, while Writer will do this in opposite way. You don't have to use both options. You can set encoding conversion only for one class - reader or writer.

Reader

Start with opening CSV file.

$reader = CsvReader::open('/path/to/file.csv');

If you need to change delimiter, enclosure or escape you can do it by passing proper values to open method. More information about these values can be found here - http://php.net/manual/en/function.fgetcsv.php.

$reader = CsvReader::open('/path/to/file.csv', ';', '\'', '\\\\');

Having your CSV file opened you can read it line after line

while (($line = $reader->readLine()) !== false) {
    print_r($line);
}

or you could read whole file at once

print_r($reader->readAll());

If your CSV file contains header line, you can convert it into array keys for each line.

$reader = CsvReader::open($file, ';');
$header = $reader->getHeader();
print_r($header);
print_r($reader->readAll());

Don't forget to close file after you're done with your work.

$reader->close();

Writer

Create new CSV file

$writer = CsvWriter::create('/path/where/your/file/will/be/saved.csv');

File path is optional. If you won't provide it CsvWriter will use memory as a storege.

If you need to change delimiter, enclosure or escape you can do it by passing proper values to create method. More information about these values can be found here - http://php.net/manual/en/function.fputcsv.php.

$writer = CsvWriter::create('/path/to/file.csv', ';', '\'', '\\\\');

To add data into CSV file you can use writeLine or writeAll methods.

$writer->writeLine(['some', 'data']);
$writer->writeLine(['another', 'line']);

$writer->writeAll([
    ['some', 'data'],
    ['another', 'line'],
]);

To display data added to CSV file use flush method.

echo $writer->flush();

Don't forget to close file after you're done with your work.

$writer->close();

Integrating with Eloquent models

If you want/need to integrate CsvReader and/or CsvWriter with Eloquent model there's a simple way of doing this. The Csv package provides three traits in order to simplify the process.

These traits hasn't been tested for handling relations. Relations are still on a TODO list

CsvCustomCollection

CsvCustomCollection trait added to model class enables toCsv method that can be used on a collection.

use Wilgucki\Csv\Traits\CsvCustomCollection;

class SomeModel extends Model
{
    use CsvCustomCollection;
    
    //...
}

$items = SomeModel::all();
$csvData = $items->toCsv();

CsvExportable

CsvExportable trait allows you to convert single model object to CSV data.

use Wilgucki\Csv\Traits\CsvExportable;

class SomeModel extends Model
{
    use CsvExportable;
    
    //...
}

$csvData = SomeModel::find(1)->toCsv();

CsvImportable

CsvImportable trait allows you to import data from CSV file and save it to the database. Imported file must have header line containing column names as they are named in database table. Primary key must be named id. CSV importer will update all rows with matching ids and add every row that isn't found in a table.

Each column from CSV file is checked against $fillable array, letting to insert or update only these columns that are present in it.

use Wilgucki\Csv\Traits\CsvImportable;

class SomeModel extends Model
{
    use CsvImportable;
    
    //...
}

SomeModel::fromCsv('/path/to/file.csv');

Command line

csv:import

To import CSV file into database table, use csv:import command.

php artisan csv:import model csv-file

  • model - model class name with its namespace
  • csv-file - file name with path relative to project's root directory

If you would like to import users, you could use command like this (remember to use correct CSV file path)

php artisan csv:import "App\User" storage/users.csv

csv:export

This command allows you to export data from database table into CSV file.

php artisan csv:export model csv-file

  • model - model's class name with its namespace
  • csv-file - file name with path relative to project's root directory

If you would like to export users, you could use command like this (remember to use correct CSV file path)

php artisan csv:export "App\User" storage/users.csv

TODO

  • handle relations

wilgucki/csv 适用场景与选型建议

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

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 284.63k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 49
  • 点击次数: 15
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 49
  • Watchers: 3
  • Forks: 6
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2015-09-10