Writer connection

The League\Csv\Writer class extends the general connections capabilities to create or update a CSV document.

When inserting records into a CSV document using League\Csv\Writer, first insert all the data that need to be inserted before starting manipulating the CSV. If you manipulate your CSV document before insertion, you may change the file cursor position and erase your data.

Inserting records

public Writer::insertOne(array $record): int
public Writer::insertAll(iterable $records): int

Writer::insertOne inserts a single record into the CSV document while Writer::insertAll adds several records. Both methods return the length of the written data.

Writer::insertOne takes a single argument, an array which represents a single CSV record. Writer::insertAll takes a single argument a PHP iterable which contains a collection of CSV records.

use League\Csv\Writer;

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', 'john.doe@example.com'],
];

$writer = Writer::from('/path/to/saved/file.csv', 'w+');
$writer->insertOne(['john', 'doe', 'john.doe@example.com']);
$writer->insertAll($records); //using an array
$writer->insertAll(new ArrayIterator($records)); //using a Traversable object

In the above example, all CSV records are saved to /path/to/saved/file.csv

If the record can not be inserted into the CSV document a League\Csv\CannotInsertRecord exception is thrown. This exception extends League\Csv\Exception and adds the ability to get the record on which the insertion failed.

use League\Csv\CannotInsertRecord;
use League\Csv\Writer;

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', 'john.doe@example.com'],
];

try {
    $writer = Writer::from('/path/to/saved/file.csv', 'r');
    $writer->insertAll($records);
} catch (CannotInsertRecord $e) {
    $e->getRecord(); //returns [1, 2, 3]
}

Since version 9.2.0 you can provide an empty string for the escape character to enable better RFC4180 compliance.

use League\Csv\Writer;

$record = ['"foo"', 'foo bar', 'baz ', 'foo\\"bar'];

$writer = Writer::fromString();
$writer->insertOne($record);
$writer->setEscape('');
$writer->insertOne($record);
echo $writer->toString();
// """foo""","foo bar","baz ","foo\"bar"
// """foo""","foo bar","baz ","foo\""bar"

The addition of this new feature means the deprecation of RFC4180Field.

You still need to set the end of line sequence as shown below

Handling end of line

Because PHP’s fputcsv implementation uses a hardcoded \n, we need to be able to replace the last LF code with one supplied by the developer for more interoperability between CSV packages on different platforms. The end of line sequence will be appended to each newly inserted CSV record.

The getEndOfLine() and setEndOfline() methods set and returns the CSV end of line used by the Writer class. The setter method expects a string sequence to be used.

setEndOfline and getEndOfLine are available since version 9.10.0.

use League\Csv\Writer;

$writer = Writer::from(new SplFileObject());
$writer->getEndOfLine();        //returns "\n";
$writer->setEndOfLine("\r\n");
$writer->getEndOfLine();        //returns "\r\n";
$writer->insertOne(["one", "two"]);
echo $writer->toString();       //displays "one,two\r\n";

setNewline and getNewLine are deprecated since version 9.10.0.

The default end of line sequence is \n;

If you are using a non-seekable CSV document, changing the end of line character will trigger an exception.

Flushing the buffer

For advanced usages, you can now manually indicate when the flushing mechanism occurs while adding new content to your CSV document.

public Writer::setFlushThreshold(?int $treshold): self
public Writer::getFlushThreshold(void): ?int

By default, getFlushTreshold returns null.

Writer::insertAll always flushes its buffer when all records are inserted, regardless of the threshold value.

If set to null the inner flush mechanism of PHP's fputcsv will be used.

Quoting

Since version 9.30.0 you can control the presence of enclosure around non-numeric and numeric fields.

Since version 9.20.0 generating CSV without enclosure is allowed.

Since version 9.10.0 you can control the presence of enclosure around all fields.

This feature controls how the Writer encloses fields when generating CSV records. It accepts any of the following League\Csv\Quoting enum cases:

  • Quoting::All: All fields are enclosed;
  • Quoting::NonNumeric: Only fields containing non-numeric data are enclosed;
  • Quoting::Minimal: Fields are enclosed according to PHP’s fputcsv() enclosure rules;
  • Quoting::EscapeOnly: No fields are enclosed; the escape character is used to escape itself, the delimiter, carriage returns, and line feeds;
  • Quoting::None: No fields are enclosed and no escaping is performed;
public Writer::setQuoting(Quoting $quoting): self
public Writer::getQuoting(): Quoting

Quoting::Minimal is used by default.

Numeric fields are identified using PHP's is_numeric() function.

The $escape character is only used when Quoting::Minimal or Quoting::EscapeOnly is selected. For all other quoting modes, it is ignored, as though it were set to an empty string.

When enclosure is disabled, the library does not validate or escape field contents. Fields containing line breaks, delimiters, or other CSV control characters may therefore produce malformed or ambiguous CSV data.

Quoting::EscapeOnly may produce CSV that cannot be read by the Reader class or PHP's fgetcsv() function. This quoting mode is intended for interoperability with CSV formats such as those supported by Apache Commons CSV.

Quoting::EscapeOnly cannot be used with an empty escape character.

Quoting::NonNumeric cannot be used when either the delimiter or enclosure character is ..

<?php
use League\Csv\Quoting;
use League\Csv\Writer;

$collection = [
    [1, 2],
    ['value 2-0', 'value 2-1'],
    ['to"to', 'foo\"bar'],
];

$writer = Writer::fromString();
$writer->getQuoting(); // returns Quoting::Minimal
$writer->setQuoting(Quoting::All);
$writer->getQuoting(); // returns Quoting::All
$writer->insertAll($collection);
echo $writer->toString(), PHP_EOL;

// all fields are enclosed.

//"1","2"
//"value 2-0","value 2-1"
//"to""to","foo\""bar"

$writer = Writer::fromString();
$writer->setQuoting(Quoting::NonNumeric);
$writer->insertAll($collection);
echo $writer->toString(), PHP_EOL;

// numeric fields are not enclosed.

//1,2
//"value 2-0","value 2-1"
//"to""to","foo\""bar"

The following methods are deprecated and will be removed in a future major release. Use setQuoting() and getQuoting() instead.

public Writer::relaxEnclosure(): self
public Writer::forceEnclosure(): self
public Writer::necessaryEnclosure(): self
public Writer::noEnclosure(): self
public Writer::encloseAll(): bool
public Writer::encloseNecessary(): bool
public Writer::encloseNone(): bool

Records filtering

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

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.

Writer::addFormatter

Record Formatter

A formatter is a callable which accepts a single CSV record as an array on input and returns an array representing the formatted CSV record according to its inner rules.

function(array $record): array

Adding a Formatter

You can attach as many formatters as you want to the Writer class using the Writer::addFormatter method. Formatters are applied following the First In First Out rule.

use League\Csv\Writer;

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

echo $writer->toString();
//will display JOHN,DOE,JOHN.DOE@EXAMPLE.COM

Writer::addValidator

Record Validator

A validator is a callable which takes a single CSV record as an array as its sole argument and returns a boolean to indicate if it satisfies the validator’s inner rules.

function(array $record): bool

The validator must return true to validate the submitted record.

Any other expression, including truthy ones like yes, 1,… will make the insertOne method throw an League\Csv\CannotInsertRecord exception.

Adding a Validator

As with the formatter capabilities, you can attach as many validators as you want using the Writer::addValidator method. Validators are applied following the First In First Out rule.

The CSV record is checked against your supplied validators after it has been formatted.

Writer::addValidator takes two (2) required parameters:

  • A validator callable;
  • A validator name. If another validator was already registered with the given name, it will be overridden.

On failure a League\Csv\CannotInsertRecord exception is thrown. This exception will give access to:

  • the validator name;
  • the record which failed the validation;
use League\Csv\Writer;
use League\Csv\CannotInsertRecord;

$writer->addValidator(function (array $row): bool {
    return 10 == count($row);
}, 'row_must_contain_10_cells');

try {
    $writer->insertOne(['john', 'doe', 'john.doe@example.com']);
} catch (CannotInsertRecord $e) {
    echo $e->getName(); //displays 'row_must_contain_10_cells'
    $e->getData();//returns the invalid data ['john', 'doe', 'john.doe@example.com']
}