-
Notifications
You must be signed in to change notification settings - Fork 494
/
SimpleXLSX.php
1221 lines (1070 loc) · 39.3 KB
/
SimpleXLSX.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php /** @noinspection MultiAssignmentUsageInspection */
namespace Shuchkin;
use SimpleXMLElement;
/**
* SimpleXLSX php class
* MS Excel 2007+ workbooks reader
*
* Copyright (c) 2012 - 2022 SimpleXLSX
*
* @category SimpleXLSX
* @package SimpleXLSX
* @copyright Copyright (c) 2012 - 2022 SimpleXLSX (https://github.com/shuchkin/simplexlsx/)
* @license MIT
*/
/** Examples
*
* use Shuchkin\SimpleXLSX;
*
* Example 1:
* if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
* foreach ($xlsx->rows() as $r) {
* print_r( $r );
* }
* } else {
* echo SimpleXLSX::parseError();
* }
*
* Example 2: html table
* if ( $xlsx = SimpleXLSX::parse('book.xlsx') ) {
* echo $xlsx->toHTML();
* } else {
* echo SimpleXLSX::parseError();
* }
*
* Example 3: rowsEx
* $xlsx = SimpleXLSX::parse('book.xlsx');
* foreach ( $xlsx->rowsEx() as $r ) {
* print_r( $r );
* }
*
* Example 4: select worksheet
* $xlsx = SimpleXLSX::parse('book.xlsx');
* foreach( $xlsx->rows(1) as $r ) { // second worksheet
* print_t( $r );
* }
*
* Example 5: IDs and worksheet names
* $xlsx = SimpleXLSX::parse('book.xlsx');
* print_r( $xlsx->sheetNames() ); // array( 0 => 'Sheet 1', 1 => 'Catalog' );
*
* Example 6: get sheet name by index
* $xlsx = SimpleXLSX::parse('book.xlsx');
* echo 'Sheet Name 2 = '.$xlsx->sheetName(1);
*
* Example 7: getCell (very slow)
* echo $xlsx->getCell(1,'D12'); // reads D12 cell from second sheet
*
* Example 8: read data
* if ( $xlsx = SimpleXLSX::parseData( file_get_contents('http://www.example.com/example.xlsx') ) ) {
* $dim = $xlsx->dimension(1);
* $num_cols = $dim[0];
* $num_rows = $dim[1];
* echo $xlsx->sheetName(1).':'.$num_cols.'x'.$num_rows;
* } else {
* echo SimpleXLSX::parseError();
* }
*
* Example 9: old style
* $xlsx = new SimpleXLSX('book.xlsx');
* if ( $xlsx->success() ) {
* print_r( $xlsx->rows() );
* } else {
* echo 'xlsx error: '.$xlsx->error();
* }
*/
class SimpleXLSX
{
// Don't remove this string! Created by Sergey Shuchkin [email protected]
public static $CF = [ // Cell formats
0 => 'General',
1 => '0',
2 => '0.00',
3 => '#,##0',
4 => '#,##0.00',
9 => '0%',
10 => '0.00%',
11 => '0.00E+00',
12 => '# ?/?',
13 => '# ??/??',
14 => 'mm-dd-yy',
15 => 'd-mmm-yy',
16 => 'd-mmm',
17 => 'mmm-yy',
18 => 'h:mm AM/PM',
19 => 'h:mm:ss AM/PM',
20 => 'h:mm',
21 => 'h:mm:ss',
22 => 'm/d/yy h:mm',
37 => '#,##0 ;(#,##0)',
38 => '#,##0 ;[Red](#,##0)',
39 => '#,##0.00;(#,##0.00)',
40 => '#,##0.00;[Red](#,##0.00)',
44 => '_("$"* #,##0.00_);_("$"* \(#,##0.00\);_("$"* "-"??_);_(@_)',
45 => 'mm:ss',
46 => '[h]:mm:ss',
47 => 'mmss.0',
48 => '##0.0E+0',
49 => '@',
27 => '[$-404]e/m/d',
30 => 'm/d/yy',
36 => '[$-404]e/m/d',
50 => '[$-404]e/m/d',
57 => '[$-404]e/m/d',
59 => 't0',
60 => 't0.00',
61 => 't#,##0',
62 => 't#,##0.00',
67 => 't0%',
68 => 't0.00%',
69 => 't# ?/?',
70 => 't# ??/??',
];
public $nf = []; // number formats
public $cellFormats = []; // cellXfs
public $datetimeFormat = 'Y-m-d H:i:s';
public $debug;
public $activeSheet = 0;
public $rowsExReader;
/* @var SimpleXMLElement[] $sheets */
public $sheets;
public $sheetFiles = [];
public $sheetMetaData = [];
public $sheetRels = [];
// scheme
public $styles;
/* @var array[] $package */
public $package;
public $sharedstrings;
public $date1904 = 0;
/*
private $date_formats = array(
0xe => "d/m/Y",
0xf => "d-M-Y",
0x10 => "d-M",
0x11 => "M-Y",
0x12 => "h:i a",
0x13 => "h:i:s a",
0x14 => "H:i",
0x15 => "H:i:s",
0x16 => "d/m/Y H:i",
0x2d => "i:s",
0x2e => "H:i:s",
0x2f => "i:s.S"
);
private $number_formats = array(
0x1 => "%1.0f", // "0"
0x2 => "%1.2f", // "0.00",
0x3 => "%1.0f", //"#,##0",
0x4 => "%1.2f", //"#,##0.00",
0x5 => "%1.0f", //"$#,##0;($#,##0)",
0x6 => '$%1.0f', //"$#,##0;($#,##0)",
0x7 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x8 => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x9 => '%1.0f%%', //"0%"
0xa => '%1.2f%%', //"0.00%"
0xb => '%1.2f', //"0.00E00",
0x25 => '%1.0f', //"#,##0;(#,##0)",
0x26 => '%1.0f', //"#,##0;(#,##0)",
0x27 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x28 => '%1.2f', //"#,##0.00;(#,##0.00)",
0x29 => '%1.0f', //"#,##0;(#,##0)",
0x2a => '$%1.0f', //"$#,##0;($#,##0)",
0x2b => '%1.2f', //"#,##0.00;(#,##0.00)",
0x2c => '$%1.2f', //"$#,##0.00;($#,##0.00)",
0x30 => '%1.0f'); //"##0.0E0";
// }}}
*/
public $errno = 0;
public $error = false;
/**
* @var false|SimpleXMLElement
*/
public $theme;
public function __construct($filename = null, $is_data = null, $debug = null)
{
if ($debug !== null) {
$this->debug = $debug;
}
$this->package = [
'filename' => '',
'mtime' => 0,
'size' => 0,
'comment' => '',
'entries' => []
];
if ($filename && $this->unzip($filename, $is_data)) {
$this->parseEntries();
}
}
public function unzip($filename, $is_data = false)
{
if ($is_data) {
$this->package['filename'] = 'default.xlsx';
$this->package['mtime'] = time();
$this->package['size'] = SimpleXLSX::strlen($filename);
$vZ = $filename;
} else {
if (!is_readable($filename)) {
$this->error(1, 'File not found ' . $filename);
return false;
}
// Package information
$this->package['filename'] = $filename;
$this->package['mtime'] = filemtime($filename);
$this->package['size'] = filesize($filename);
// Read file
$vZ = file_get_contents($filename);
}
// Cut end of central directory
/* $aE = explode("\x50\x4b\x05\x06", $vZ);
if (count($aE) == 1) {
$this->error('Unknown format');
return false;
}
*/
// Explode to each part
$aE = explode("\x50\x4b\x03\x04", $vZ);
array_shift($aE);
$aEL = count($aE);
if ($aEL === 0) {
$this->error(2, 'Unknown archive format');
return false;
}
// Search central directory end record
$last = $aE[$aEL - 1];
$last = explode("\x50\x4b\x05\x06", $last);
if (count($last) !== 2) {
$this->error(2, 'Unknown archive format');
return false;
}
// Search central directory
$last = explode("\x50\x4b\x01\x02", $last[0]);
if (count($last) < 2) {
$this->error(2, 'Unknown archive format');
return false;
}
$aE[$aEL - 1] = $last[0];
// Loop through the entries
foreach ($aE as $vZ) {
$aI = [];
$aI['E'] = 0;
$aI['EM'] = '';
// Retrieving local file header information
// $aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL', $vZ);
$aP = unpack('v1VN/v1GPF/v1CM/v1FT/v1FD/V1CRC/V1CS/V1UCS/v1FNL/v1EFL', $vZ);
// Check if data is encrypted
// $bE = ($aP['GPF'] && 0x0001) ? TRUE : FALSE;
// $bE = false;
$nF = $aP['FNL'];
$mF = $aP['EFL'];
// Special case : value block after the compressed data
if ($aP['GPF'] & 0x0008) {
$aP1 = unpack('V1CRC/V1CS/V1UCS', SimpleXLSX::substr($vZ, -12));
$aP['CRC'] = $aP1['CRC'];
$aP['CS'] = $aP1['CS'];
$aP['UCS'] = $aP1['UCS'];
// 2013-08-10
$vZ = SimpleXLSX::substr($vZ, 0, -12);
if (SimpleXLSX::substr($vZ, -4) === "\x50\x4b\x07\x08") {
$vZ = SimpleXLSX::substr($vZ, 0, -4);
}
}
// Getting stored filename
$aI['N'] = SimpleXLSX::substr($vZ, 26, $nF);
$aI['N'] = str_replace('\\', '/', $aI['N']);
if (SimpleXLSX::substr($aI['N'], -1) === '/') {
// is a directory entry - will be skipped
continue;
}
// Truncate full filename in path and filename
$aI['P'] = dirname($aI['N']);
$aI['P'] = ($aI['P'] === '.') ? '' : $aI['P'];
$aI['N'] = basename($aI['N']);
$vZ = SimpleXLSX::substr($vZ, 26 + $nF + $mF);
if ($aP['CS'] > 0 && (SimpleXLSX::strlen($vZ) !== (int)$aP['CS'])) { // check only if availabled
$aI['E'] = 1;
$aI['EM'] = 'Compressed size is not equal with the value in header information.';
}
// } elseif ( $bE ) {
// $aI['E'] = 5;
// $aI['EM'] = 'File is encrypted, which is not supported from this class.';
/* } else {
switch ($aP['CM']) {
case 0: // Stored
// Here is nothing to do, the file ist flat.
break;
case 8: // Deflated
$vZ = gzinflate($vZ);
break;
case 12: // BZIP2
if (extension_loaded('bz2')) {
$vZ = bzdecompress($vZ);
} else {
$aI['E'] = 7;
$aI['EM'] = 'PHP BZIP2 extension not available.';
}
break;
default:
$aI['E'] = 6;
$aI['EM'] = "De-/Compression method {$aP['CM']} is not supported.";
}
if (!$aI['E']) {
if ($vZ === false) {
$aI['E'] = 2;
$aI['EM'] = 'Decompression of data failed.';
} elseif ($this->_strlen($vZ) !== (int)$aP['UCS']) {
$aI['E'] = 3;
$aI['EM'] = 'Uncompressed size is not equal with the value in header information.';
} elseif (crc32($vZ) !== $aP['CRC']) {
$aI['E'] = 4;
$aI['EM'] = 'CRC32 checksum is not equal with the value in header information.';
}
}
}
*/
// DOS to UNIX timestamp
$aI['T'] = mktime(
($aP['FT'] & 0xf800) >> 11,
($aP['FT'] & 0x07e0) >> 5,
($aP['FT'] & 0x001f) << 1,
($aP['FD'] & 0x01e0) >> 5,
$aP['FD'] & 0x001f,
(($aP['FD'] & 0xfe00) >> 9) + 1980
);
$this->package['entries'][] = [
'data' => $vZ,
'ucs' => (int)$aP['UCS'], // ucompresses size
'cm' => $aP['CM'], // compressed method
'cs' => isset($aP['CS']) ? (int) $aP['CS'] : 0, // compresses size
'crc' => $aP['CRC'],
'error' => $aI['E'],
'error_msg' => $aI['EM'],
'name' => $aI['N'],
'path' => $aI['P'],
'time' => $aI['T']
];
} // end for each entries
return true;
}
public function error($num = null, $str = null)
{
if ($num) {
$this->errno = $num;
$this->error = $str;
if ($this->debug) {
trigger_error(__CLASS__ . ': ' . $this->error, E_USER_WARNING);
}
}
return $this->error;
}
public function parseEntries()
{
// Document data holders
$this->sharedstrings = [];
$this->sheets = [];
// $this->styles = array();
// $m1 = 0; // memory_get_peak_usage( true );
// Read relations and search for officeDocument
if ($relations = $this->getEntryXML('_rels/.rels')) {
foreach ($relations->Relationship as $rel) {
$rel_type = basename(trim((string)$rel['Type'])); // officeDocument
$rel_target = SimpleXLSX::getTarget('', (string)$rel['Target']); // /xl/workbook.xml or xl/workbook.xml
if ($rel_type === 'officeDocument'
&& $workbook = $this->getEntryXML($rel_target)
) {
$index_rId = []; // [0 => rId1]
$index = 0;
foreach ($workbook->sheets->sheet as $s) {
$a = [];
foreach ($s->attributes() as $k => $v) {
$a[(string)$k] = (string)$v;
}
$this->sheetMetaData[$index] = $a;
$index_rId[$index] = (string)$s['id'];
$index++;
}
if ((int)$workbook->workbookPr['date1904'] === 1) {
$this->date1904 = 1;
}
if ($workbookRelations = $this->getEntryXML(dirname($rel_target) . '/_rels/workbook.xml.rels')) {
// Loop relations for workbook and extract sheets...
foreach ($workbookRelations->Relationship as $workbookRelation) {
$wrel_type = basename(trim((string)$workbookRelation['Type'])); // worksheet
$wrel_target = SimpleXLSX::getTarget(dirname($rel_target), (string)$workbookRelation['Target']);
if (!$this->entryExists($wrel_target)) {
continue;
}
if ($wrel_type === 'worksheet') { // Sheets
if ($sheet = $this->getEntryXML($wrel_target)) {
$index = array_search((string)$workbookRelation['Id'], $index_rId, true);
$this->sheets[$index] = $sheet;
$this->sheetFiles[$index] = $wrel_target;
$srel_d = dirname($wrel_target);
$srel_f = basename($wrel_target);
$srel_file = $srel_d . '/_rels/' . $srel_f . '.rels';
if ($this->entryExists($srel_file)) {
$this->sheetRels[$index] = $this->getEntryXML($srel_file);
}
}
} elseif ($wrel_type === 'sharedStrings') {
if ($sharedStrings = $this->getEntryXML($wrel_target)) {
foreach ($sharedStrings->si as $val) {
if (isset($val->t)) {
$this->sharedstrings[] = (string)$val->t;
} elseif (isset($val->r)) {
$this->sharedstrings[] = SimpleXLSX::parseRichText($val);
}
}
}
} elseif ($wrel_type === 'styles') {
$this->styles = $this->getEntryXML($wrel_target);
// number formats
$this->nf = [];
if (isset($this->styles->numFmts->numFmt)) {
foreach ($this->styles->numFmts->numFmt as $v) {
$this->nf[(int)$v['numFmtId']] = (string)$v['formatCode'];
}
}
$this->cellFormats = [];
if (isset($this->styles->cellXfs->xf)) {
foreach ($this->styles->cellXfs->xf as $v) {
$x = [
'format' => null
];
foreach ($v->attributes() as $k1 => $v1) {
$x[ $k1 ] = (int) $v1;
}
if (isset($x['numFmtId'])) {
if (isset($this->nf[$x['numFmtId']])) {
$x['format'] = $this->nf[$x['numFmtId']];
} elseif (isset(self::$CF[$x['numFmtId']])) {
$x['format'] = self::$CF[$x['numFmtId']];
}
}
$this->cellFormats[] = $x;
}
}
} elseif ($wrel_type === 'theme') {
$this->theme = $this->getEntryXML($wrel_target);
}
}
// break;
}
// reptile hack :: find active sheet from workbook.xml
if ($workbook->bookViews->workbookView) {
foreach ($workbook->bookViews->workbookView as $v) {
if (!empty($v['activeTab'])) {
$this->activeSheet = (int)$v['activeTab'];
}
}
}
break;
}
}
}
// $m2 = memory_get_peak_usage(true);
// echo __FUNCTION__.' M='.round( ($m2-$m1) / 1048576, 2).'MB'.PHP_EOL;
if (count($this->sheets)) {
// Sort sheets
ksort($this->sheets);
return true;
}
return false;
}
public function getEntryXML($name)
{
if ($entry_xml = $this->getEntryData($name)) {
$this->deleteEntry($name); // economy memory
// dirty remove namespace prefixes and empty rows
$entry_xml = preg_replace('/xmlns[^=]*="[^"]*"/i', '', $entry_xml); // remove namespaces
$entry_xml .= ' '; // force run garbage collector
$entry_xml = preg_replace('/[a-zA-Z0-9]+:([a-zA-Z0-9]+="[^"]+")/', '$1', $entry_xml); // remove namespaced attrs
$entry_xml .= ' ';
$entry_xml = preg_replace('/<[a-zA-Z0-9]+:([^>]+)>/', '<$1>', $entry_xml); // fix namespaced openned tags
$entry_xml .= ' ';
$entry_xml = preg_replace('/<\/[a-zA-Z0-9]+:([^>]+)>/', '</$1>', $entry_xml); // fix namespaced closed tags
$entry_xml .= ' ';
if (strpos($name, '/sheet')) { // dirty skip empty rows
// remove <row...> <c /><c /></row>
$entry_xml = preg_replace('/<row[^>]+>\s*(<c[^\/]+\/>\s*)+<\/row>/', '', $entry_xml, -1, $cnt);
$entry_xml .= ' ';
// remove <row />
$entry_xml = preg_replace('/<row[^\/>]*\/>/', '', $entry_xml, -1, $cnt2);
$entry_xml .= ' ';
// remove <row...></row>
$entry_xml = preg_replace('/<row[^>]*><\/row>/', '', $entry_xml, -1, $cnt3);
$entry_xml .= ' ';
if ($cnt || $cnt2 || $cnt3) {
$entry_xml = preg_replace('/<dimension[^\/]+\/>/', '', $entry_xml);
$entry_xml .= ' ';
}
// file_put_contents( basename( $name ), $entry_xml ); // @to do comment!!!
}
$entry_xml = trim($entry_xml);
// $m1 = memory_get_usage();
// XML External Entity (XXE) Prevention, libxml_disable_entity_loader deprecated in PHP 8
if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) {
$_old = libxml_disable_entity_loader();
}
$_old_uie = libxml_use_internal_errors(true);
$entry_xmlobj = simplexml_load_string($entry_xml, 'SimpleXMLElement', LIBXML_COMPACT | LIBXML_PARSEHUGE);
libxml_use_internal_errors($_old_uie);
if (LIBXML_VERSION < 20900 && function_exists('libxml_disable_entity_loader')) {
/** @noinspection PhpUndefinedVariableInspection */
libxml_disable_entity_loader($_old);
}
// $m2 = memory_get_usage();
// echo round( ($m2-$m1) / (1024 * 1024), 2).' MB'.PHP_EOL;
if ($entry_xmlobj) {
return $entry_xmlobj;
}
$e = libxml_get_last_error();
if ($e) {
$this->error(3, 'XML-entry ' . $name . ' parser error ' . $e->message . ' line ' . $e->line);
}
} else {
$this->error(4, 'XML-entry not found ' . $name);
}
return false;
}
// sheets numeration: 1,2,3....
public function getEntryData($name)
{
$name = ltrim(str_replace('\\', '/', $name), '/');
$dir = SimpleXLSX::strtoupper(dirname($name));
$name = SimpleXLSX::strtoupper(basename($name));
foreach ($this->package['entries'] as &$entry) {
if (SimpleXLSX::strtoupper($entry['path']) === $dir && SimpleXLSX::strtoupper($entry['name']) === $name) {
if ($entry['error']) {
return false;
}
switch ($entry['cm']) {
case -1:
case 0: // Stored
// Here is nothing to do, the file ist flat.
break;
case 8: // Deflated
$entry['data'] = gzinflate($entry['data']);
break;
case 12: // BZIP2
if (extension_loaded('bz2')) {
$entry['data'] = bzdecompress($entry['data']);
} else {
$entry['error'] = 7;
$entry['error_message'] = 'PHP BZIP2 extension not available.';
}
break;
default:
$entry['error'] = 6;
$entry['error_msg'] = 'De-/Compression method '.$entry['cm'].' is not supported.';
}
if (!$entry['error'] && $entry['cm'] > -1) {
$entry['cm'] = -1;
if ($entry['data'] === false) {
$entry['error'] = 2;
$entry['error_msg'] = 'Decompression of data failed.';
} elseif ($entry['ucs'] > 0 && (SimpleXLSX::strlen($entry['data']) !== (int)$entry['ucs'])) {
$entry['error'] = 3;
$entry['error_msg'] = 'Uncompressed size is not equal with the value in header information.';
} elseif (crc32($entry['data']) !== $entry['crc']) {
$entry['error'] = 4;
$entry['error_msg'] = 'CRC32 checksum is not equal with the value in header information.';
}
}
return $entry['data'];
}
}
unset($entry);
$this->error(5, 'Entry not found ' . ($dir ? $dir . '/' : '') . $name);
return false;
}
public function deleteEntry($name)
{
$name = ltrim(str_replace('\\', '/', $name), '/');
$dir = SimpleXLSX::strtoupper(dirname($name));
$name = SimpleXLSX::strtoupper(basename($name));
foreach ($this->package['entries'] as $k => $entry) {
if (SimpleXLSX::strtoupper($entry['path']) === $dir && SimpleXLSX::strtoupper($entry['name']) === $name) {
unset($this->package['entries'][$k]);
return true;
}
}
return false;
}
public static function strtoupper($str)
{
return (ini_get('mbstring.func_overload') & 2) ? mb_strtoupper($str, '8bit') : strtoupper($str);
}
/*
* @param string $name Filename in archive
* @return SimpleXMLElement|bool
*/
public function entryExists($name)
{
// 0.6.6
$dir = SimpleXLSX::strtoupper(dirname($name));
$name = SimpleXLSX::strtoupper(basename($name));
foreach ($this->package['entries'] as $entry) {
if (SimpleXLSX::strtoupper($entry['path']) === $dir && SimpleXLSX::strtoupper($entry['name']) === $name) {
return true;
}
}
return false;
}
public static function parseFile($filename, $debug = false)
{
return self::parse($filename, false, $debug);
}
public static function parse($filename, $is_data = false, $debug = false)
{
$xlsx = new self();
$xlsx->debug = $debug;
if ($xlsx->unzip($filename, $is_data)) {
$xlsx->parseEntries();
}
if ($xlsx->success()) {
return $xlsx;
}
self::parseError($xlsx->error());
self::parseErrno($xlsx->errno());
return false;
}
public function success()
{
return !$this->error;
}
// https://github.com/shuchkin/simplexlsx#gets-extend-cell-info-by--rowsex
public static function parseError($set = false)
{
static $error = false;
return $set ? $error = $set : $error;
}
public static function parseErrno($set = false)
{
static $errno = false;
return $set ? $errno = $set : $errno;
}
public function errno()
{
return $this->errno;
}
public static function parseData($data, $debug = false)
{
return self::parse($data, true, $debug);
}
public function worksheet($worksheetIndex = 0)
{
if (isset($this->sheets[$worksheetIndex])) {
return $this->sheets[$worksheetIndex];
}
$this->error(6, 'Worksheet not found ' . $worksheetIndex);
return false;
}
/**
* returns [numCols,numRows] of worksheet
*
* @param int $worksheetIndex
*
* @return array
*/
public function dimension($worksheetIndex = 0)
{
if (($ws = $this->worksheet($worksheetIndex)) === false) {
return [0, 0];
}
/* @var SimpleXMLElement $ws */
$ref = (string)$ws->dimension['ref'];
if (SimpleXLSX::strpos($ref, ':') !== false) {
$d = explode(':', $ref);
$idx = $this->getIndex($d[1]);
return [$idx[0] + 1, $idx[1] + 1];
}
/*
if ( $ref !== '' ) { // 0.6.8
$index = $this->getIndex( $ref );
return [ $index[0] + 1, $index[1] + 1 ];
}
*/
// slow method
$maxC = $maxR = 0;
$iR = -1;
foreach ($ws->sheetData->row as $row) {
$iR++;
$iC = -1;
foreach ($row->c as $c) {
$iC++;
$idx = $this->getIndex((string)$c['r']);
$x = $idx[0];
$y = $idx[1];
if ($x > -1) {
if ($x > $maxC) {
$maxC = $x;
}
if ($y > $maxR) {
$maxR = $y;
}
} else {
if ($iC > $maxC) {
$maxC = $iC;
}
if ($iR > $maxR) {
$maxR = $iR;
}
}
}
}
return [$maxC + 1, $maxR + 1];
}
public function getIndex($cell = 'A1')
{
if (preg_match('/([A-Z]+)(\d+)/', $cell, $m)) {
$col = $m[1];
$row = $m[2];
$colLen = SimpleXLSX::strlen($col);
$index = 0;
for ($i = $colLen - 1; $i >= 0; $i--) {
$index += (ord($col[$i]) - 64) * pow(26, $colLen - $i - 1);
}
return [$index - 1, $row - 1];
}
// $this->error( 'Invalid cell index ' . $cell );
return [-1, -1];
}
public function value($cell)
{
// Determine data type
$dataType = (string)$cell['t'];
if ($dataType === '' || $dataType === 'n') { // number
$s = (int)$cell['s'];
if ($s > 0 && isset($this->cellFormats[$s])) {
if (array_key_exists('format', $this->cellFormats[$s])) {
$format = $this->cellFormats[$s]['format'];
if ($format && preg_match('/[mM]/', preg_replace('/\"[^"]+\"/', '', $format))) { // [mm]onth,AM|PM
$dataType = 'D';
}
} else {
$dataType = 'n';
}
}
}
$value = '';
switch ($dataType) {
case 's':
// Value is a shared string
if ((string)$cell->v !== '') {
$value = $this->sharedstrings[(int)$cell->v];
}
break;
case 'str': // formula?
if ((string)$cell->v !== '') {
$value = (string)$cell->v;
}
break;
case 'b':
// Value is boolean
$value = (string)$cell->v;
if ($value === '0') {
$value = false;
} elseif ($value === '1') {
$value = true;
} else {
$value = (bool)$cell->v;
}
break;
case 'inlineStr':
// Value is rich text inline
$value = SimpleXLSX::parseRichText($cell->is);
break;
case 'e':
// Value is an error message
if ((string)$cell->v !== '') {
$value = (string)$cell->v;
}
break;
case 'D':
// Date as float
if (!empty($cell->v)) {
$value = $this->datetimeFormat ? gmdate($this->datetimeFormat, $this->unixstamp((float)$cell->v)) : (float)$cell->v;
}
break;
case 'd':
// Date as ISO YYYY-MM-DD
if ((string)$cell->v !== '') {
$value = (string)$cell->v;
}
break;
default:
// Value is a string
$value = (string)$cell->v;
// Check for numeric values
if (is_numeric($value)) {
/** @noinspection TypeUnsafeComparisonInspection */
if ($value == (int)$value) {
$value = (int)$value;
} /** @noinspection TypeUnsafeComparisonInspection */ elseif ($value == (float)$value) {
$value = (float)$value;
}
}
}
return $value;
}
public function unixstamp($excelDateTime)
{
$d = floor($excelDateTime); // days since 1900 or 1904
$t = $excelDateTime - $d;
if ($this->date1904) {
$d += 1462;
}
$t = (abs($d) > 0) ? ($d - 25569) * 86400 + round($t * 86400) : round($t * 86400);
return (int)$t;
}
public function toHTML($worksheetIndex = 0)
{
$s = '<table class=excel>';
foreach ($this->readRows($worksheetIndex) as $r) {
$s .= '<tr>';
foreach ($r as $c) {
$s .= '<td nowrap>' . ($c === '' ? ' ' : htmlspecialchars($c, ENT_QUOTES)) . '</td>';
}
$s .= "</tr>\r\n";
}
$s .= '</table>';
return $s;
}
public function toHTMLEx($worksheetIndex = 0)
{
$s = '<table class=excel>';
$y = 0;
foreach ($this->readRowsEx($worksheetIndex) as $r) {
$s .= '<tr>';
$x = 0;
foreach ($r as $c) {
$tag = 'td';
$css = $c['css'];
if ($y === 0) {
$tag = 'th';
$css .= $c['width'] ? 'width: '.round($c['width'] * 0.47, 2).'em;' : '';
}
if ($x === 0 && $c['height']) {
$css .= 'height: '.round($c['height'] * 1.3333).'px;';
}
$s .= '<'.$tag.' style="'.$css.'" nowrap>' . ($c['value'] === '' ? ' ' : htmlspecialchars($c['value'], ENT_QUOTES)) . '</'.$tag.'>';
$x++;
}
$s .= "</tr>\r\n";
$y++;
}
$s .= '</table>';
return $s;
}
public function rows($worksheetIndex = 0, $limit = 0)
{
return iterator_to_array($this->readRows($worksheetIndex, $limit), false);
}
// thx Gonzo
/**
* @param $worksheetIndex
* @param $limit
* @return \Generator
*/
public function readRows($worksheetIndex = 0, $limit = 0)
{
if (($ws = $this->worksheet($worksheetIndex)) === false) {