-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathCsvWriter.php
More file actions
82 lines (69 loc) · 1.76 KB
/
CsvWriter.php
File metadata and controls
82 lines (69 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace Port\Csv;
use Port\Writer\AbstractStreamWriter;
/**
* Writes to a CSV file
*
* @author David de Boer <david@ddeboer.nl>
*/
class CsvWriter extends AbstractStreamWriter
{
/**
* @var string
*/
private $delimiter;
/**
* @var string
*/
private $enclosure;
/**
* @var boolean
*/
private $utf8Encoding = false;
private $row = 1;
/**
* @var boolean
*/
protected $prependHeaderRow;
/**
* @var string
*/
private $escape;
/**
* @param string $delimiter The delimiter
* @param string $enclosure The enclosure
* @param resource $stream
* @param boolean $utf8Encoding
* @param boolean $prependHeaderRow
* @param string $escape
*/
public function __construct($delimiter = ',', $enclosure = '"', $stream = null, $utf8Encoding = false, $prependHeaderRow = false, $escape = '\\')
{
parent::__construct($stream);
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
$this->utf8Encoding = $utf8Encoding;
$this->prependHeaderRow = $prependHeaderRow;
$this->escape = $escape;
}
/**
* {@inheritdoc}
*/
public function prepare()
{
if ($this->utf8Encoding) {
fprintf($this->getStream(), chr(0xEF) . chr(0xBB) . chr(0xBF));
}
}
/**
* {@inheritdoc}
*/
public function writeItem(array $item)
{
if ($this->prependHeaderRow && 1 == $this->row++) {
$headers = array_keys($item);
fputcsv($this->getStream(), $headers, $this->delimiter, $this->enclosure, $this->escape);
}
fputcsv($this->getStream(), $item, $this->delimiter, $this->enclosure, $this->escape);
}
}