1: <?php
2:
3: namespace SimpleExcel\Parser;
4:
5: use SimpleExcel\Enums\Datatype;
6: use SimpleExcel\Enums\SimpleExcelException;
7: use SimpleExcel\Spreadsheet\Cell;
8: use SimpleExcel\Spreadsheet\Workbook;
9: use SimpleExcel\Spreadsheet\Worksheet;
10:
11: 12: 13: 14: 15: 16:
17: class XMLParser extends BaseParser
18: {
19: 20: 21: 22: 23: 24:
25: protected $file_extension = 'xml';
26:
27: 28: 29: 30: 31: 32: 33:
34: protected function parseDOM ($xml) {
35: $this->workbook = new Workbook();
36: $xmlns = $xml->getDocNamespaces();
37: if ($xmlns['ss'] != 'urn:schemas-microsoft-com:office:spreadsheet') {
38: throw new \Exception('Document namespace isn\'t a valid Excel XML 2003 Spreadsheet', SimpleExcelException::INVALID_DOCUMENT_NAMESPACE);
39: }
40: foreach($xml->Worksheet as $worksheet) {
41: $sheet = new Worksheet();
42: $col_max = 0;
43: foreach ($worksheet->Table->Row as $row) {
44: $record = array();
45: $row_index = $row->xpath('@ss:Index');
46: if (count($row_index) > 0) {
47: $gap = $row_index[0] - count($sheet->getRecords());
48: for($i = 1; $i < $gap; $i++){
49: $sheet->insertRecord(array());
50: }
51: }
52: $record = array();
53: $col_num = 0;
54: foreach ($row->Cell as $cell) {
55: $cell_index = $cell->xpath('@ss:Index');
56: if (count($cell_index) > 0) {
57: $gap = $cell_index[0] - count($record);
58: for ($i = 1; $i < $gap; $i++) {
59: array_push($record, new Cell(''));
60: }
61: }
62: $data_attrs = $cell->Data->xpath('@ss:*');
63: $cell_datatype = $data_attrs['Type'];
64: switch ($cell_datatype) {
65: case 'Number':
66: $cell_datatype = Datatype::NUMBER;
67: break;
68: case 'DateTime':
69: $cell_datatype = Datatype::DATETIME;
70: break;
71: case 'Error':
72: $cell_datatype = Datatype::ERROR;
73: break;
74: case 'String':
75: default:
76: $cell_datatype = Datatype::TEXT;
77: }
78: $cell_value = (string) $cell->Data;
79: array_push($record, new Cell($cell_value, $cell_datatype));
80: $col_num += 1;
81: }
82: if ($col_num > $col_max) {
83: $col_max = $col_num;
84: }
85: $sheet->insertRecord($record);
86: }
87: foreach ($sheet->getRecords() as $i => $record) {
88: if (($diff = $col_max - count($record)) > 0) {
89: $record = $sheet->getRecord($i + 1);
90: for ($j = 0; $j < $diff; $j++) {
91: array_push($record, new Cell(''));
92: }
93: }
94: }
95: $this->workbook->insertWorksheet($sheet);
96: }
97: }
98:
99: 100: 101: 102: 103: 104: 105:
106: public function loadFile($file_path, $options = NULL) {
107: if ($this->checkFile($file_path)) {
108: $this->parseDOM(simplexml_load_file($file_path));
109: }
110: }
111:
112: 113: 114: 115: 116: 117: 118:
119: public function loadString ($str, $options = NULL) {
120: $this->parseDOM(simplexml_load_string($str));
121: }
122: }
123: