From 467dfac2fb6bfa4eb9ccf85394bc956c09878f73 Mon Sep 17 00:00:00 2001 From: Michel Roca Date: Mon, 28 Jul 2014 11:02:59 +0200 Subject: [PATCH 1/2] Add UTF-8 encoding to CsvWriter --- src/Ddeboer/DataImport/Writer/CsvWriter.php | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/src/Ddeboer/DataImport/Writer/CsvWriter.php b/src/Ddeboer/DataImport/Writer/CsvWriter.php index ee68acb7..b73e797f 100644 --- a/src/Ddeboer/DataImport/Writer/CsvWriter.php +++ b/src/Ddeboer/DataImport/Writer/CsvWriter.php @@ -9,6 +9,7 @@ class CsvWriter extends AbstractStreamWriter { private $delimiter = ';'; private $enclosure = '"'; + private $utf8Encoding = false; /** * Constructor @@ -16,13 +17,27 @@ class CsvWriter extends AbstractStreamWriter * @param string $delimiter The delimiter * @param string $enclosure The enclosure * @param resource $stream + * @param bool $utf8Encoding */ - public function __construct($delimiter = ';', $enclosure = '"', $stream = null) + public function __construct($delimiter = ';', $enclosure = '"', $stream = null, $utf8Encoding = false) { parent::__construct($stream); $this->delimiter = $delimiter; $this->enclosure = $enclosure; + $this->utf8Encoding = $utf8Encoding; + } + + /** + * @inheritdoc + */ + public function prepare() + { + if ($this->utf8Encoding) { + fprintf($this->getStream(), chr(0xEF) . chr(0xBB) . chr(0xBF)); + } + + return $this; } /** From bb09dfcb96ff9319902bea80a129ca3bc2c8c08f Mon Sep 17 00:00:00 2001 From: Michel Roca Date: Mon, 28 Jul 2014 13:00:50 +0200 Subject: [PATCH 2/2] Add Test for UTF-8 encoding to CsvWriter --- .../DataImport/Tests/Writer/CsvWriterTest.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php b/tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php index 35108ee3..5990cd78 100644 --- a/tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php +++ b/tests/Ddeboer/DataImport/Tests/Writer/CsvWriterTest.php @@ -10,6 +10,7 @@ public function testWriteItem() { $writer = new CsvWriter(';', '"', $this->getStream()); + $writer->prepare(); $writer->writeItem(array('first', 'last')); $writer @@ -29,6 +30,21 @@ public function testWriteItem() $writer->finish(); } + public function testWriteUtf8Item() + { + $writer = new CsvWriter(';', '"', $this->getStream(), true); + + $writer->prepare(); + $writer->writeItem(array('Précédent', 'Suivant')); + + $this->assertContentsEquals( + chr(0xEF) . chr(0xBB) . chr(0xBF) . "Précédent;Suivant\n", + $writer + ); + + $writer->finish(); + } + public function testFluentInterface() { $writer = new CsvWriter(';', '"', $this->getStream());