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         
35         print_R($ret);exit;
36         
37         $this->jdata($ret['data'], false, isset($ret['extra']) ? $ret['extra'] : array() );
38         
39     }
40     
41     function importCsv($csv)
42     {
43         ini_set("auto_detect_line_endings", true);
44         
45         $fh = fopen($csv, 'r');
46         if (!$fh) {
47             $this->jerr("invalid file");
48         }
49         
50          
51         $cols = false;
52         $header = false;
53         $rows = array();
54         $extra = array();
55         
56         while(false !== ($n = fgetcsv($fh,10000, ',', '"'))) {
57             if(!array_filter($n)){
58                 if ($header) {
59                     continue;
60                 }
61                 $header = true;
62                 continue;
63             }
64             
65             if(!$header){
66                $extra[preg_replace(array('/\s/', '/\:/'), '', $n[0])] = $n[1];
67                continue;
68             }
69             
70             if(!$cols){
71                 $cols = array();
72                 foreach($n as $k) {
73                     $cols[] = strtoupper(trim($k));
74                 }
75                 
76                 if (empty($cols)) {
77                     continue;
78                 }
79                
80            
81                 continue;
82             }
83             
84             foreach($cols as $i=>$k) {
85                 $row[$k] = $n[$i];
86             }
87             $rows[] = $row;
88             
89         }
90         fclose($fh);
91         
92         $ret = array('extra' => $extra, 'data' => $rows);
93         echo 'about to return?';print_R($ret);exit;
94         
95         return array('extra' => $extra, 'data' => $rows);;
96     }
97 }