ExcelToJson.php
[Pman.Core] / ExcelToJson.php
1 <?php
2
3 require_once 'Pman/Roo.php';
4
5 class Pman_Core_ExcelToJson extends Pman_Roo
6 {
7     function getAuth()
8     {
9         if (HTML_FlexyFramework::get()->cli) {
10             return true;
11         }
12         return parent::getAuth();
13     }
14     
15     function post()
16     {
17         $this->transObj = DB_DataObject::Factory('invhist_transfer');
18         
19         $this->transObj->query('BEGIN');
20         
21         PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'onPearError'));
22         
23         $img = DB_DataObject::Factory('images');
24         $img->setFrom(array(
25             'onid' => 0,
26             'ontable' => 'ipshead'
27         ));
28         $img->onUpload(false);
29         
30         require_once 'File/Convert.php';
31         $fc = new File_Convert($img->getStoreName(), $img->mimetype );
32         $csv = $fc->convert('text/csv');
33         $ret = $this->importCsv($csv);
34         $this->jdata($ret['data'], false, isset($ret['extra']) ? $ret['extra'] : array() );
35         
36     }
37     
38     function importCsv($csv)
39     {
40         ini_set("auto_detect_line_endings", true);
41         
42         $fh = fopen($csv, 'r');
43         if (!$fh) {
44             $this->jerr("invalid file");
45         }
46         
47          
48         $cols = false;
49         $header = false;
50         $rows = array();
51         $ret = array();
52         
53         while(false !== ($n = fgetcsv($fh,10000, ',', '"'))) {
54             if(!array_filter($n)){
55                 if ($header) {
56                     continue;
57                 }
58                 $header = true;
59                 continue;
60             }
61             
62             if(!$header){
63                $ret[preg_replace(array('/\s/', '/\:/'), '', $n[0])] = $n[1];
64                continue;
65             }
66             
67             if(!$cols){
68                 $cols = array();
69                 foreach($n as $k) {
70                     $cols[] = strtoupper(trim($k));
71                 }
72                 
73                 if (empty($cols)) {
74                     continue;
75                 }
76                
77            
78                 continue;
79             }
80             
81             foreach($cols as $i=>$k) {
82                 $row[$k] = $n[$i];
83             }
84             $rows[] = $row;
85             
86         }
87         fclose($fh);
88         
89         return array('extra' => $ret, 'data' => $rows);;
90     }
91 }