/
ExcelToJson.php
98 lines (70 loc) · 2.34 KB
/
ExcelToJson.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
<?php
require_once 'Pman/Roo.php';
class Pman_Core_ExcelToJson extends Pman_Roo
{
function getAuth()
{
if (HTML_FlexyFramework::get()->cli) {
return true;
}
return parent::getAuth();
}
function post($v)
{
$this->transObj = DB_DataObject::Factory('invhist_transfer');
$this->transObj->query('BEGIN');
PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
$img = DB_DataObject::Factory('images');
$img->setFrom(array(
'onid' => 0,
'ontable' => 'ipshead'
));
$img->onUpload(false);
require_once 'File/Convert.php';
$fc = new File_Convert($img->getStoreName(), $img->mimetype );
$csv = $fc->convert('text/csv');
$ret = $this->importCsv($csv);
$this->jdata($ret['data'], false, isset($ret['extra']) ? $ret['extra'] : array() );
}
function importCsv($csv)
{
ini_set("auto_detect_line_endings", true);
$fh = fopen($csv, 'r');
if (!$fh) {
$this->jerr("invalid file");
}
$cols = false;
$header = false;
$rows = array();
$extra = array();
while(false !== ($n = fgetcsv($fh,10000, ',', '"'))) {
if(!strlen(trim(implode('', $n)))){ // blank line;
if ($header) {
continue;
}
$header = true;
continue;
}
if(!$header){
$extra[preg_replace(array('/\s/', '/\:/'), '', $n[0])] = $n[1];
continue;
}
if(!$cols){
$cols = array();
foreach($n as $k) {
$cols[] = strtoupper(trim($k));
}
if (empty($cols)) {
continue;
}
continue;
}
foreach($cols as $i=>$k) {
$row[$k] = $n[$i];
}
$rows[] = $row;
}
fclose($fh);
return array('extra' => $extra, 'data' => $rows);;
}
}