1: <?php
 2: 
 3: namespace SimpleExcel\Parser;
 4: 
 5: use SimpleExcel\Enums\SimpleExcelException;
 6: use SimpleExcel\Spreadsheet\Cell;
 7: use SimpleExcel\Spreadsheet\Workbook;
 8: use SimpleExcel\Spreadsheet\Worksheet;
 9: 
10: 11: 12: 13: 14: 15:  
16: class JSONParser extends BaseParser
17: {    
18:     19: 20: 21: 22: 23: 
24:     protected $file_extension = 'json';
25:     
26:     27: 28: 29: 30: 31: 
32:     public function loadFile ($file_path, $options = NULL) {    
33:         if ($this->checkFile($file_path)) {
34:             $handle = fopen($file_path, 'r');
35:             $contents = fread($handle, filesize($file_path));
36:             $this->loadString($contents, $options);
37:             fclose($handle);
38:         }
39:     }
40:     
41:     42: 43: 44: 45: 46: 47: 
48:     public function loadString ($str, $options = NULL) {
49:         $this->workbook = new Workbook();
50:         if (($workbook = json_decode(utf8_encode($str), false, 5)) === NULL) {
51:             throw new \Exception('Invalid JSON format: '.$str, SimpleExcelException::MALFORMED_JSON);
52:         } else {
53:             foreach ($workbook as $worksheet) {
54:                 $sheet = new Worksheet();
55:                 $rows = array();
56:                 foreach ($worksheet as $record) {
57:                     $row = array();
58:                     foreach ($record as $cell) {
59:                         array_push($row, new Cell($cell));
60:                     }
61:                     array_push($rows, $row);
62:                 }
63:                 $sheet->setRecords($rows);
64:                 $this->workbook->insertWorksheet($sheet);
65:             }
66:         }
67:     }
68: }
69: