CSVParser.php
5.93 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
/**
* Class to handle parsing of CSV files, where the column headers are in the
* first row.
*
* The idea is that you pass it another object to handle the actual processing
* of the data in the CSV file.
*
* Usage:
*
* <code>
* $parser = new CSVParser('myfile.csv');
* $parser->mapColumns(
* 'first name' => 'FirstName'
* 'lastname' => 'Surname',
* 'last name' => 'Surname'
* ));
* foreach($parser as $row) {
* // $row is a map of column name => column value
* $obj = new MyDataObject();
* $obj->update($row);
* $obj->write();
* }
* </code>
*
* @package framework
* @subpackage bulkloading
*/
class CSVParser extends Object implements Iterator {
/**
* @var string $filename
*/
protected $filename;
/**
* @var resource $fileHandle
*/
protected $fileHandle;
/**
* Map of source columns to output columns.
*
* Once they get into this variable, all of the source columns are in
* lowercase.
*
* @var array
*/
protected $columnMap = array();
/**
* The header row used to map data in the CSV file.
*
* To begin with, this is null. Once it has been set, data will get
* returned from the CSV file.
*
* @var array
*/
protected $headerRow = null;
/**
* A custom header row provided by the caller.
*
* @var array
*/
protected $providedHeaderRow = null;
/**
* The data of the current row.
*
* @var array
*/
protected $currentRow = null;
/**
* The current row number.
*
* 1 is the first data row in the CSV file; the header row, if it exists,
* is ignored.
*
* @var int
*/
protected $rowNum = 0;
/**
* The character for separating columns.
*
* @var string
*/
protected $delimiter = ",";
/**
* The character for quoting columns.
*
* @var string
*/
protected $enclosure = '"';
/**
* Open a CSV file for parsing.
*
* You can use the object returned in a foreach loop to extract the data.
*
* @param $filename The name of the file. If relative, it will be relative to the site's base dir
* @param $delimiter The character for seperating columns
* @param $enclosure The character for quoting or enclosing columns
*/
public function __construct($filename, $delimiter = ",", $enclosure = '"') {
$filename = Director::getAbsFile($filename);
$this->filename = $filename;
$this->delimiter = $delimiter;
$this->enclosure = $enclosure;
parent::__construct();
}
/**
* Re-map columns in the CSV file.
*
* This can be useful for identifying synonyms in the file. For example:
*
* <code>
* $csv->mapColumns(array(
* 'firstname' => 'FirstName',
* 'last name' => 'Surname',
* ));
* </code>
*
* @param array
*/
public function mapColumns($columnMap) {
if($columnMap) {
$lowerColumnMap = array();
foreach($columnMap as $k => $v) {
$lowerColumnMap[strtolower($k)] = $v;
}
$this->columnMap = array_merge($this->columnMap, $lowerColumnMap);
}
}
/**
* If your CSV file doesn't have a header row, then you can call this
* function to provide one.
*
* If you call this function, then the first row of the CSV will be
* included in the data returned.
*
* @param array
*/
public function provideHeaderRow($headerRow) {
$this->providedHeaderRow = $headerRow;
}
/**
* Open the CSV file for reading.
*/
protected function openFile() {
ini_set('auto_detect_line_endings',1);
$this->fileHandle = fopen($this->filename,'r');
if($this->providedHeaderRow) {
$this->headerRow = $this->remapHeader($this->providedHeaderRow);
}
}
/**
* Close the CSV file and re-set all of the internal variables.
*/
protected function closeFile() {
if($this->fileHandle) {
fclose($this->fileHandle);
}
$this->fileHandle = null;
$this->rowNum = 0;
$this->currentRow = null;
$this->headerRow = null;
}
/**
* Get a header row from the CSV file.
*/
protected function fetchCSVHeader() {
$srcRow = fgetcsv(
$this->fileHandle,
0,
$this->delimiter,
$this->enclosure
);
$this->headerRow = $this->remapHeader($srcRow);
}
/**
* Map the contents of a header array using $this->mappedColumns.
*
* @param array
*
* @return array
*/
protected function remapHeader($header) {
$mappedHeader = array();
foreach($header as $item) {
if(isset($this->columnMap[strtolower($item)])) {
$item = $this->columnMap[strtolower($item)];
}
$mappedHeader[] = $item;
}
return $mappedHeader;
}
/**
* Get a row from the CSV file and update $this->currentRow;
*
* @return array
*/
protected function fetchCSVRow() {
if(!$this->fileHandle) {
$this->openFile();
}
if(!$this->headerRow) {
$this->fetchCSVHeader();
}
$this->rowNum++;
$srcRow = fgetcsv(
$this->fileHandle,
0,
$this->delimiter,
$this->enclosure
);
if($srcRow) {
$row = array();
foreach($srcRow as $i => $value) {
// Allow escaping of quotes and commas in the data
$value = str_replace(
array('\\'.$this->enclosure,'\\'.$this->delimiter),
array($this->enclosure, $this->delimiter),
$value
);
if(array_key_exists($i, $this->headerRow)) {
if($this->headerRow[$i]) {
$row[$this->headerRow[$i]] = $value;
}
} else {
user_error("No heading for column $i on row $this->rowNum", E_USER_WARNING);
}
}
$this->currentRow = $row;
} else {
$this->closeFile();
}
return $this->currentRow;
}
/**
* @ignore
*/
public function __destruct() {
$this->closeFile();
}
//// ITERATOR FUNCTIONS
/**
* @ignore
*/
public function rewind() {
$this->closeFile();
$this->fetchCSVRow();
}
/**
* @ignore
*/
public function current() {
return $this->currentRow;
}
/**
* @ignore
*/
public function key() {
return $this->rowNum;
}
/**
* @ignore
*/
public function next() {
$this->fetchCSVRow();
return $this->currentRow;
}
/**
* @ignore
*/
public function valid() {
return $this->currentRow ? true : false;
}
}