-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcsv2json.php
68 lines (55 loc) · 1.27 KB
/
csv2json.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
62
63
64
65
66
67
<?php
function csvToArray($file, $delimiter) {
if (($handle = fopen($file, 'r')) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter, '"')) !== FALSE) {
for ($j = 0; $j < count($lineArray); $j++) {
$arr[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $arr;
}
if(isset($_POST['url'])) {
header('Content-type: application/json');
$feed = $_POST['url'];
$keys = array();
$newArray = array();
$data = csvToArray($feed, ',');
$count = count($data) - 1;
//eka rivi on otsikot
$labels = array_shift($data);
foreach ($labels as $label) {
$keys[] = $label;
}
//lisätään ID:t
$keys[] = 'id';
for ($i = 0; $i < $count; $i++) {
$data[$i][] = $i;
}
//lisätään yhteen arrayhin
for ($j = 0; $j < $count; $j++) {
$d = array_combine($keys, $data[$j]);
$newArray[$j] = $d;
}
//tulostetaan JSON:iksi
echo json_encode($newArray);
} else {
?>
<!DOCTYPE html>
<html>
<head>
<title>CSV to JSON converter \o/</title>
</head>
<body>
<form action="scrape.php" method="post">
<input type="text" name="url" size="100" placeholder="Syötä url-osoite.." required />
<input type="submit" name="submit" value="Käännä JSON:iksi" />
</form>
</body>
</html>
<?php
}
?>