The League of Extraordinary Packages

Our Packages:

Presented by The League of Extraordinary Packages

Getting Started

Connections

Inserting Records

Selecting Records

Converting Records

Upgrading Guide

This is the documentation for the upcoming version 9.0. This is a work in progress

Insertion Filtering

<?php

public Writer::addFormatter(callable $callable): Writer
public Writer::addValidator(callable $callable, string $validatorName): Writer

Sometimes you may want to format and/or validate your records prior to their insertion into your CSV document. the Writer class provides a formatter and a validator mechanism to ease these operations.

Record Formatter

A formatter is a callable which accepts an array on input and returns a formatted array according to its inner rules.

<?php

function(array $record): array

You can attach as many formatters as you want to the Writer class to manipulate your data prior to its insertion use the Writer::addFormatter method. The formatters follow the First In First Out rule when applied.

<?php

public Writer::addFormatter(callable $callable): Writer

Example

<?php

use League\Csv\Writer;

$formatter = function ($row) {
    return array_map('strtoupper', $row);
};
$writer = Writer::createFromFileObject(new SplTempFileObject());
$writer->addFormatter($formatter);
$writer->insertOne(['john', 'doe', 'john.doe@example.com']);

$writer->__toString();
//will display something like JOHN,DOE,JOHN.DOE@EXAMPLE.COM

Record Validator

A validator is a callable which takes an array as its sole argument and returns a boolean.

<?php

function(array $record): bool

The validator must return true to validate the submitted record.

Any other expression, including thruthy ones like yes, 1,… will make the insertOne method throw an League\Csv\Exception\InsertionException.

As with the formatter capabilities, you can attach as many validators as you want to your data prior to its insertion using the Writer::addValidator method. The record data is checked against your supplied validators after it has been formatted.

<?php

public Writer::addValidator(callable $callable, string $validatorName): Writer

Writer::addValidator takes two parameters:

On failure a League\Csv\Exception\InsertionException exception is thrown by the Writer object.

Example

<?php

use League\Csv\Writer;
use League\Csv\Exception\InsertionException;

$writer->addValidator(function (array $row) {
    return 10 == count($row);
}, 'row_must_contain_10_cells');
try {
    $writer->insertOne(['john', 'doe', 'john.doe@example.com']);
} catch (InsertionException $e) {
    echo $e->getName(); //display 'row_must_contain_10_cells'
    $e->getData();//will return the invalid data ['john', 'doe', 'john.doe@example.com']
}

Bundled formatters

Null value formatting

The League\Csv\Plugin\SkipNullValuesFormatter class skips cell using founded null values

<?php

use League\Csv\Writer;
use League\Csv\Plugin\SkipNullValuesFormatter;

$formatter = new SkipNullValuesFormatter();

$writer = Writer::createFromPath('/path/to/your/csv/file.csv');
$writer->addFormatter($formatter);
$writer->insertOne(["foo", null, "bar"]);
//the actual inserted row will be ["foo", "bar"]

Records encoder

<?php

public Encoder::inputEncoding(string $input_encoding): self
public Encoder::outputEncoding(string $output_encoding): self
public Encoder::__invoke(array $record): array

League\Csv\Encoder will help you encode your record depending on your settings.

<?php

use League\Csv\Encoder;
use League\Csv\Writer;

$writer = Writer::createFromPath('/path/to/your/csv/file.csv');
$encoder = (new Encoder())
    ->inputEncoding('utf-8')
    ->outputEncoding('iso-8859-15')
;
$writer->addFormatter($encoder);
$writer->insertOne(["foo", "bébé", "jouet"]);
//all 'utf-8' caracters are now automatically encoded into 'iso-8859-15' charset

Tip: If your Writer object supports PHP stream filters then it's recommended to use the library stream filtering mechanism instead.

Tip: The Encoder object can also be used to convert CSV records into other transport/exchange format.

Bundled validators

Null value validator

The League\Csv\Plugin\ForbiddenNullValuesValidator class validates the absence of null values

<?php

use League\Csv\Writer;
use League\Csv\Plugin\ForbiddenNullValuesValidator;

$validator = new ForbiddenNullValuesValidator();
$writer = Writer::createFromPath('/path/to/your/csv/file.csv');
$writer->addValidator($validator, 'null_as_exception');
$writer->insertOne(["foo", null, "bar"]); //will throw an League\Csv\Exception\InsertionException

Records consistency check

<?php

public ColumnConsistencyValidator::setColumnsCount(int $count): void
public ColumnConsistencyValidator::getColumnsCount(void): int
public ColumnConsistencyValidator::autodetectColumnsCount(void): void

The League\Csv\Plugin\ColumnConsistencyValidator class validates the inserted record column count consistency.

<?php

use League\Csv\Writer;
use League\Csv\Plugin\ColumnConsistencyValidator;

$validator = new ColumnConsistencyValidator();
$validator->autodetectColumnsCount();
$validator->getColumnsCount(); //returns -1

$writer = Writer::createFromPath('/path/to/your/csv/file.csv');
$writer->addValidator($validator, 'column_consistency');

$writer->insertOne(["foo", null, "bar"]);
$nb_column_count = $validator->getColumnsCount(); //returns 3