|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Ddeboer\DataImport\Writer; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Writes to a CSV file |
|
7
|
|
|
* |
|
8
|
|
|
* @author David de Boer <[email protected]> |
|
9
|
|
|
*/ |
|
10
|
|
|
class CsvWriter extends AbstractStreamWriter |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* @var string |
|
14
|
|
|
*/ |
|
15
|
|
|
private $delimiter = ';'; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var string |
|
19
|
|
|
*/ |
|
20
|
|
|
private $enclosure = '"'; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @var boolean |
|
24
|
|
|
*/ |
|
25
|
|
|
private $utf8Encoding = false; |
|
26
|
|
|
private $row = 1; |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @var boolean |
|
30
|
|
|
*/ |
|
31
|
|
|
protected $prependHeaderRow; |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* @param string $delimiter The delimiter |
|
35
|
|
|
* @param string $enclosure The enclosure |
|
36
|
|
|
* @param resource $stream |
|
37
|
|
|
* @param boolean $utf8Encoding |
|
38
|
|
|
*/ |
|
39
|
4 |
|
public function __construct($delimiter = ';', $enclosure = '"', $stream = null, $utf8Encoding = false, $prependHeaderRow = false) |
|
40
|
|
|
{ |
|
41
|
4 |
|
parent::__construct($stream); |
|
42
|
|
|
|
|
43
|
4 |
|
$this->delimiter = $delimiter; |
|
44
|
4 |
|
$this->enclosure = $enclosure; |
|
45
|
4 |
|
$this->utf8Encoding = $utf8Encoding; |
|
46
|
|
|
|
|
47
|
4 |
|
$this->prependHeaderRow = $prependHeaderRow; |
|
48
|
4 |
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* {@inheritdoc} |
|
52
|
|
|
*/ |
|
53
|
4 |
|
public function prepare() |
|
54
|
|
|
{ |
|
55
|
4 |
|
if ($this->utf8Encoding) { |
|
56
|
1 |
|
fprintf($this->getStream(), chr(0xEF) . chr(0xBB) . chr(0xBF)); |
|
57
|
1 |
|
} |
|
58
|
4 |
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* {@inheritdoc} |
|
62
|
|
|
*/ |
|
63
|
4 |
|
public function writeItem(array $item) |
|
64
|
|
|
{ |
|
65
|
4 |
|
if ($this->prependHeaderRow && 1 == $this->row++) { |
|
66
|
1 |
|
$headers = array_keys($item); |
|
67
|
1 |
|
fputcsv($this->getStream(), $headers, $this->delimiter, $this->enclosure); |
|
68
|
1 |
|
} |
|
69
|
|
|
|
|
70
|
4 |
|
fputcsv($this->getStream(), $item, $this->delimiter, $this->enclosure); |
|
71
|
4 |
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|