Laravel 5 package for writing and reading CSV files

1.0 2018-07-15 11:27 UTC

This package is auto-updated.

Last update: 2024-11-11 14:41:36 UTC


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