Skip to content

Commit cbae2f5

Browse files
committed
Merge pull request #102 from mRoca/master
Add UTF-8 encoding to CsvWriter
2 parents c84f6cc + bb09dfc commit cbae2f5

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/Ddeboer/DataImport/Writer/CsvWriter.php

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,20 +9,35 @@ class CsvWriter extends AbstractStreamWriter
99
{
1010
private $delimiter = ';';
1111
private $enclosure = '"';
12+
private $utf8Encoding = false;
1213

1314
/**
1415
* Constructor
1516
*
1617
* @param string $delimiter The delimiter
1718
* @param string $enclosure The enclosure
1819
* @param resource $stream
20+
* @param bool $utf8Encoding
1921
*/
20-
public function __construct($delimiter = ';', $enclosure = '"', $stream = null)
22+
public function __construct($delimiter = ';', $enclosure = '"', $stream = null, $utf8Encoding = false)
2123
{
2224
parent::__construct($stream);
2325

2426
$this->delimiter = $delimiter;
2527
$this->enclosure = $enclosure;
28+
$this->utf8Encoding = $utf8Encoding;
29+
}
30+
31+
/**
32+
* @inheritdoc
33+
*/
34+
public function prepare()
35+
{
36+
if ($this->utf8Encoding) {
37+
fprintf($this->getStream(), chr(0xEF) . chr(0xBB) . chr(0xBF));
38+
}
39+
40+
return $this;
2641
}
2742

2843
/**

tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ public function testWriteItem()
1010
{
1111
$writer = new CsvWriter(';', '"', $this->getStream());
1212

13+
$writer->prepare();
1314
$writer->writeItem(array('first', 'last'));
1415

1516
$writer
@@ -29,6 +30,21 @@ public function testWriteItem()
2930
$writer->finish();
3031
}
3132

33+
public function testWriteUtf8Item()
34+
{
35+
$writer = new CsvWriter(';', '"', $this->getStream(), true);
36+
37+
$writer->prepare();
38+
$writer->writeItem(array('Précédent', 'Suivant'));
39+
40+
$this->assertContentsEquals(
41+
chr(0xEF) . chr(0xBB) . chr(0xBF) . "Précédent;Suivant\n",
42+
$writer
43+
);
44+
45+
$writer->finish();
46+
}
47+
3248
public function testFluentInterface()
3349
{
3450
$writer = new CsvWriter(';', '"', $this->getStream());

0 commit comments

Comments
 (0)