<commit_before>---
layout: default
title: CSV document Writer connection
---

# Writer connection

~~~php
<?php

class Writer extends AbstractCsv
{
    public function addFormatter(callable $callable): Writer
    public function addValidator(callable $callable, string $validatorName): Writer
    public function getFlushThreshold(): ?int
    public function getNewline(): string
    public function insertAll(iterable $records): int
    public function insertOne(array $record): int
    public function setFlushThreshold(?int $threshold): self
    public function setNewline(string $sequence): self
}
~~~

The `League\Csv\Writer` class extends the general connections [capabilities](/9.0/connections/) to create or update a CSV document.

<p class="message-warning">When inserting records into a CSV document using <code>League\Csv\Writer</code>, 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.</p>

## Inserting records

~~~php
<?php

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 returns 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.

~~~php
<?php

use League\Csv\Writer;

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', '<EMAIL>'],
];

$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne(['john', 'doe', '<EMAIL>']);
$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.

~~~php
<?php

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

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', '<EMAIL>'],
];

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

<p class="message-info">Since version <code>9.2.0</code> you can provide an empty string for the escape character to enable better <a href="https://tools.ietf.org/html/rfc4180">RFC4180</a> compliance.</p>

~~~php
<?php

use League\Csv\Writer;

$records = [
    ['foo', 'foo bar', 'baz '],

];

$writer = Writer::createFromString('');
$writer->insertOne(['"foo"', 'foo bar', 'baz ', 'foo\\bar']);
$writer->setEscape('');
$writer->insertOne(['"foo"', 'foo bar', 'baz ', 'foo\\bar']);
echo $writer->getContents();
// """foo""","foo bar","baz ","foo\bar"
// """foo""",foo bar,"baz ",foo\bar
~~~

<p class="message-notice">The addition of this new feature means the deprecation of <a href="/9.0/interoperability/rfc4180-field/">RFC4180Field</a>.</p>

<p class="message-notice">You still need to set the newline sequence as shown below</p>

## Handling newline

Because PHP's `fputcsv` implementation has 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 newline sequence will be appended to each newly inserted CSV record.<commit_msg>fix Writer::insertOne example with setEscape<commit_after>---
layout: default
title: CSV document Writer connection
---

# Writer connection

~~~php
<?php

class Writer extends AbstractCsv
{
    public function addFormatter(callable $callable): Writer
    public function addValidator(callable $callable, string $validatorName): Writer
    public function getFlushThreshold(): ?int
    public function getNewline(): string
    public function insertAll(iterable $records): int
    public function insertOne(array $record): int
    public function setFlushThreshold(?int $threshold): self
    public function setNewline(string $sequence): self
}
~~~

The `League\Csv\Writer` class extends the general connections [capabilities](/9.0/connections/) to create or update a CSV document.

<p class="message-warning">When inserting records into a CSV document using <code>League\Csv\Writer</code>, 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.</p>

## Inserting records

~~~php
<?php

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 returns 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.

~~~php
<?php

use League\Csv\Writer;

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', '<EMAIL>'],
];

$writer = Writer::createFromPath('/path/to/saved/file.csv', 'w+');
$writer->insertOne(['john', 'doe', '<EMAIL>']);
$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.

~~~php
<?php

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

$records = [
    [1, 2, 3],
    ['foo', 'bar', 'baz'],
    ['john', 'doe', '<EMAIL>'],
];

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

<p class="message-info">Since version <code>9.2.0</code> you can provide an empty string for the escape character to enable better <a href="https://tools.ietf.org/html/rfc4180">RFC4180</a> compliance.</p>

~~~php
<?php

use League\Csv\Writer;

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

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

<p class="message-notice">The addition of this new feature means the deprecation of <a href="/9.0/interoperability/rfc4180-field/">RFC4180Field</a>.</p>

<p class="message-notice">You still need to set the newline sequence as shown below</p>

## Handling newline

Because PHP's `fputcsv` implementation has 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 newline sequence will be appended to each newly inserted CSV record.
{'fraction_non_alphanumeric': 0.14446227929373998, 'fraction_numerical': 0.008560727661851257, 'mean_word_length': 4.873527101335428, 'pattern_counts': {'":': 0, '<': 51, '<?xml version=': 0, '>': 59, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7115534', 'n_tokens_mistral': 2303, 'n_tokens_neox': 2174, 'n_words': 804}