-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSVReader.php
48 lines (41 loc) · 1.51 KB
/
CSVReader.php
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
<?php
class CSVReader
{
private $csvFileName;
private $headerMapping;
private $delimiter; // delimiter property
public function __construct($csvFileName, $delimiter = ',')
{
$this->csvFileName = $csvFileName;
$this->delimiter = $delimiter; // Store the delimiter
// Define header mapping
$this->headerMapping = [
'brand_name' => 'make',
'model_name' => 'model',
'condition_name' => 'condition',
'grade_name' => 'grade',
'gb_spec_name' => 'capacity',
'colour_name' => 'colour',
'network_name' => 'network',
];
}
public function readCSV()
{
$data = [];
if (($handle = fopen($this->csvFileName, "r")) !== false) {
$header = fgetcsv($handle,0, $this->delimiter); // Get the header row with the specified delimiter
// Map header names to object properties
$header = array_map(function ($header) {
return $this->headerMapping[$header] ?? $header;
}, $header);
while (($row = fgetcsv($handle, 0, $this->delimiter)) !== false) { // Use the specified delimiter
$record = array_combine($header, $row);
$data[] = $record;
}
fclose($handle);
} else {
throw new Exception("Error: Unable to open the CSV file '{$this->csvFileName}' for reading.");
}
return $data;
}
}