-
Notifications
You must be signed in to change notification settings - Fork 78
/
json2csv.class.php
115 lines (97 loc) · 2.63 KB
/
json2csv.class.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
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
<?php
class JSON2CSVutil{
public $dataArray;
public $isNested = FALSE;
function readJSON($JSONdata){
$this->dataArray = json_decode($JSONdata,1);
$this->prependColumnNames();
return $this->dataArray;
}
function JSONfromFile($file){
$this->dataArray = json_decode(file_get_contents($file),1);
$this->prependColumnNames();
return $this->dataArray;
}
private function prependColumnNames(){
foreach(array_keys($this->dataArray[0]) as $key){
$keys[0][$key] = $key;
}
$this->dataArray = array_merge($keys, $this->dataArray);
}
function save2CSV($file){
if($this->isItNested() || !is_array($this->dataArray)){
echo "JSON is either invalid or has nested elements.";
}
else{
$fileIO = fopen($file, 'w+');
foreach ($this->dataArray as $fields) {
fputcsv($fileIO, $fields);
}
fclose($fileIO);
}
}
function flatten2CSV($file){
$fileIO = fopen($file, 'w+');
foreach ($this->dataArray as $items) {
$flatData = array();
$fields = new RecursiveIteratorIterator(new RecursiveArrayIterator($items));
foreach($fields as $value) {
array_push($flatData, $value);
}
fputcsv($fileIO, $flatData, ";", '"');
}
fclose($fileIO);
}
function browserDL($CSVname){
if($this->isItNested() || !is_array($this->dataArray)){
echo "<h1>JSON is either invalid or has nested elements.</h1>";
}
else{
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$CSVname");
$output = fopen('php://output', 'w');
foreach ($this->dataArray as $fields) {
fputcsv($output, $fields);
}
}
}
function flattenDL($CSVname){
header("Content-Type: text/csv; charset=utf-8");
header("Content-Disposition: attachment; filename=$CSVname");
$output = fopen("php://output", "w");
foreach ($this->dataArray as $items) {
$flatData = array();
$fields = new RecursiveIteratorIterator(new RecursiveArrayIterator($items));
foreach($fields as $value) {
array_push($flatData, $value);
}
fputcsv($output, $flatData, ";", '"');
}
}
private function isItNested(){
foreach($this->dataArray as $data){
if(is_array($data)){
$isNested = TRUE;
break 1;
}
}
return $this->isNested;
}
function savejson2csv($JSONdata, $file){
$this->readJSON($JSONdata);
$this->save2CSV($file);
}
function flattenjson2csv($JSONdata, $file){
$this->readJSON($JSONdata);
$this->flatten2CSV($file);
}
function savejsonFile2csv($file, $destFile){
$this->JSONfromFile($file);
$this->save2CSV($destFile);
}
function flattenjsonFile2csv($file, $destFile){
$this->JSONfromFile($file);
$this->flatten2CSV($destFile);
}
}
?>