-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparseCSV.php
61 lines (50 loc) · 1.67 KB
/
parseCSV.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
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
function getTitle($filePath)
{
if (($handle = fopen($filePath, "r")) !== FALSE) {
// Luetaan vain ensimmäinen rivi
$FirstTitle = fgetcsv($handle, 0, ',');
if (!$FirstTitle) {
fclose($handle);
return null;
}
fclose($handle);
return $FirstTitle;
} else {
die('failed');
}
}
function parseCSV($filePath)
{
if (($handle = fopen($filePath, "r")) !== FALSE) {
fgets($handle);
fgets($handle);
fgets($handle);
$objects = [];
$keys = fgetcsv($handle, 0, ','); // Hae otsikkorivi
if (!$keys) {
fclose($handle);
return null;
}
while (($data = fgetcsv($handle, 0, ',')) !== FALSE) {
// Tarkista, että rivi sisältää tarvittavan määrän sarakkeita
if (count($data) === count($keys)) {
// Convert the encoding of each item to UTF-8 if necessary
$encodedData = array_map(function ($item) {
// Attempt to detect encoding and convert to UTF-8 if not already
$encoding = mb_detect_encoding($item, mb_detect_order(), true);
return $encoding == "UTF-8" ? $item : utf8_encode($item);
}, $data);
$rowArray = array_combine($keys, $encodedData);
$objects[] = (object)$rowArray;
}
}
fclose($handle);
return $objects;
} else {
die('failed');
}
}
$csvFilePath = __DIR__ . '/data/alkon-hinnasto-tekstitiedostona.csv';
$FirstTitle = getTitle($csvFilePath);
$dataObjects = parseCSV($csvFilePath);