forked from danmandle/JSON2CSV
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjson2csv.class.php
56 lines (44 loc) · 1.15 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
<?php
class JSON2CSVutil{
public $dataArray;
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){
$fileIO = fopen($file, 'w+');
foreach ($this->dataArray as $fields) {
fputcsv($fileIO, $fields);
}
fclose($fileIO);
}
function browserDL($CSVname){
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 savejson2csv($JSONdata, $file){
$this->readJSON($JSONdata);
$this->save2CSV($file);
}
function savejsonFile2csv($file, $destFile){
$this->JSONfromFile($file);
$this->save2CSV($destFile);
}
}
?>