This repository has been archived by the owner on May 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
csv2json
executable file
·72 lines (58 loc) · 1.87 KB
/
csv2json
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
#!/usr/bin/php
<?php
/*
* CSV2JSON PHP script
* This script converts a CSV file to a JSON object. It expects all values to
* be enclosed in double quotes (") and to be seperated by commas (,)
*
* Written by Hay Kranen < http://www.haykranen.nl > < hay at bykr dot org >
*
* USE
* Make this executable
* $ chmod u+x csv2json
* Then invoke it from the command line like this
* $ csv2json myfile.csv
* The script will automatically write the resulting file as myfile.json
*/
function quit($msg) {
die($msg . "\n");
}
// For PHP < 5.3
if (!function_exists('str_getcsv')) {
function str_getcsv($input, $delimiter = ",", $enclosure = '"', $escape = "\\") {
$fiveMBs = 5 * 1024 * 1024;
$fp = fopen("php://temp/maxmemory:$fiveMBs", 'r+');
fputs($fp, $input);
rewind($fp);
$data = fgetcsv($fp, 1000, $delimiter, $enclosure); // $escape only got added in 5.3.0
fclose($fp);
return $data;
}
}
$filename = $argv[1];
if (!file_exists($filename)) quit("File does not exist: $filename");
$file = file($filename);
if (!$file) quit("File read error with $filanme");
echo "Processing $filename... \n";
$data = array();
// Get the first line for the values
$hash = str_getcsv($file[0]);
unset($file[0]);
foreach ($file as $line) {
// Create new array for the line
$values = str_getcsv($line);
$obj = array();
foreach ($values as $index => $value) {
$key = $hash[$index];
$obj[$key] = $value;
}
$data[] = $obj;
}
echo "Ready..now writing to JSON\n";
$json = json_encode($data);
if (!$json) quit("Could not encode to JSON");
// Create a filename based on the input file
$out = pathinfo($filename, PATHINFO_FILENAME) . ".json";
if(file_exists($out)) quit("File already exists! Aborting!");
if(!file_put_contents($out, $json)) quit("Could not write contents to $out");
quit("Written JSON data to $out");