Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
### Unreleased

### v2.3.1 (2025-03-12)

* Support option to customize EOL character in CSVWriter

### v2.3.0 (2025-03-10)

* Support option to write CSV column headers unquoted
Expand Down
7 changes: 4 additions & 3 deletions src/CSV/CSVWriter.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class CSVWriter
protected $options = [
'write_utf8_bom' => FALSE,
'quote_headers' => TRUE,
'eol' => "\n",
];

/**
Expand Down Expand Up @@ -79,7 +80,7 @@ public function write(array $row)
throw MismatchedSchemaException::forSchema($this->expect_schema, $row_schema);
}

\fputcsv($this->resource, $row);
\fputcsv($this->resource, $row, eol: $this->options['eol']);
}

protected function isResourceOpen()
Expand All @@ -103,7 +104,7 @@ public function close()
private function writeHeaders(array $keys): void
{
if ($this->options['quote_headers']) {
\fputcsv($this->resource, $keys);
\fputcsv($this->resource, $keys, eol: $this->options['eol']);
} else {
array_walk(
$keys,
Expand All @@ -112,7 +113,7 @@ private function writeHeaders(array $keys): void
"Column header `$str` cannot contain comma if headers are not quoted"
)
);
fwrite($this->resource, implode(',', $keys).PHP_EOL);
fwrite($this->resource, implode(',', $keys).$this->options['eol']);
}
}
}
42 changes: 42 additions & 0 deletions test/unit/CSV/CSVWriterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,48 @@ public function test_it_throws_if_column_headers_contain_comma_when_unquoted():
fclose($file);
}

public static function providerLineEndings(): array
{
return [
'default' => [
[],
"\"our big\",is\ndata,here\n",
],
'default, with unquoted headers' => [
['quote_headers' => false],
"our big,is\ndata,here\n",
],
'unix' => [
['eol' => "\n"],
"\"our big\",is\ndata,here\n",
],
'mac' => [
['eol' => "\r"],
"\"our big\",is\rdata,here\r",
],
'windows' => [
['eol' => "\r\n"],
"\"our big\",is\r\ndata,here\r\n",
],
'windows, with unquoted headers' => [
['eol' => "\r\n", 'quote_headers' => false],
"our big,is\r\ndata,here\r\n",
],
];
}

#[DataProvider('providerLineEndings')]
public function test_its_line_endings_can_be_configured(array $options, string $expect): void
{
$file = fopen('php://memory', 'w');
$subj = $this->newSubject();
$subj->open($file, $options);
$subj->write(['our big' => 'data', 'is' => 'here']);
rewind($file);
$this->assertSame($expect, stream_get_contents($file));
fclose($file);
}

#[TestWith([true])]
#[TestWith([false])]
public function test_it_optionally_writes_byte_order_mark_at_start_of_file($write_bom)
Expand Down
Loading