-
Notifications
You must be signed in to change notification settings - Fork 0
/
tableExtractor.php
383 lines (283 loc) · 9.41 KB
/
tableExtractor.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
<?php
/*----------------------------------------------------------------------
Table Extractor
===============
Table extractor is a php class that can extract almost any table
from any html document/page, and then convert that html table into
a php array.
Version 1.3
Compatibility: PHP 4.4.1 +
Copyright Jack Sleight - www.reallyshiny.com
This script is licensed under the Creative Commons License.
----------------------------------------------------------------------*/
class tableExtractor {
var $source = NULL;
var $anchor = NULL;
var $anchorWithin = false;
var $headerRow = true;
var $startRow = 1;
var $maxRows = 0;
var $startCol = 1;
var $maxCols = 0;
var $stripTags = false;
var $extraCols = array();
var $rowCount = 0;
var $dropRows = NULL;
var $cleanHTML = NULL;
var $rawArray = NULL;
var $finalArray = NULL;
/*--------------------------------------------------
--------------------------------------------------*/
function extractTable() {
$this->cleanHTML();
$this->prepareArray();
return $this->createArray();
}
/*--------------------------------------------------
--------------------------------------------------*/
function cleanHTML() {
// php 4 compatibility functions
if(!function_exists('stripos')) {
function stripos($haystack,$needle,$offset = 0) {
return(strpos(strtolower($haystack),strtolower($needle),$offset));
}
}
// find unique string that appears before the table you want to extract
if ($this->anchorWithin) {
/*------------------------------------------------------------
With thanks to Khary Sharp for suggesting and writing
the anchor within functionality.
------------------------------------------------------------*/
$anchorPos = stripos($this->source, $this->anchor) + strlen($this->anchor);
$sourceSnippet = strrev(substr($this->source, 0, $anchorPos));
$tablePos = stripos($sourceSnippet, strrev(("<table"))) + 6;
$startSearch = strlen($sourceSnippet) - $tablePos;
}
else {
$startSearch = stripos($this->source, $this->anchor);
}
// extract table
$startTable = stripos($this->source, '<table', $startSearch);
$endTable = stripos($this->source, '</table>', $startTable) + 8;
$table = substr($this->source, $startTable, $endTable - $startTable);
if(!function_exists('lcase_tags')) {
function lcase_tags($input) {
return strtolower($input[0]);
}
}
// lowercase all table related tags
$table = preg_replace_callback('/<(\/?)(table|tr|th|td)/is', 'lcase_tags', $table);
// remove all thead and tbody tags
$table = preg_replace('/<\/?(thead|tbody).*?>/is', '', $table);
// replace th tags with td tags
$table = preg_replace('/<(\/?)th(.*?)>/is', '<$1td$2>', $table);
// clean string
$table = trim($table);
$table = str_replace("\r\n", "", $table);
$this->cleanHTML = $table;
}
/*--------------------------------------------------
--------------------------------------------------*/
function prepareArray() {
// split table into individual elements
$pattern = '/(<\/?(?:tr|td).*?>)/is';
$table = preg_split($pattern, $this->cleanHTML, -1, PREG_SPLIT_DELIM_CAPTURE);
// define array for new table
$tableCleaned = array();
// define variables for looping through table
$rowCount = 0;
$colCount = 1;
$trOpen = false;
$tdOpen = false;
// loop through table
foreach($table as $item) {
// trim item
$item = str_replace(' ', '', $item);
$item = trim($item);
// save the item
$itemUnedited = $item;
// clean if tag
$item = preg_replace('/<(\/?)(table|tr|td).*?>/is', '<$1$2>', $item);
// pick item type
switch ($item) {
case '<tr>':
// start a new row
$rowCount++;
$colCount = 1;
$trOpen = true;
break;
case '<td>':
// save the td tag for later use
$tdTag = $itemUnedited;
$tdOpen = true;
break;
case '</td>':
$tdOpen = false;
break;
case '</tr>':
$trOpen = false;
break;
default :
// if a TD tag is open
if($tdOpen) {
// check if td tag contained colspan
if(preg_match('/<td [^>]*colspan\s*=\s*(?:\'|")?\s*([0-9]+)[^>]*>/is', $tdTag, $matches))
$colspan = $matches[1];
else
$colspan = 1;
// check if td tag contained rowspan
if(preg_match('/<td [^>]*rowspan\s*=\s*(?:\'|")?\s*([0-9]+)[^>]*>/is', $tdTag, $matches))
$rowspan = $matches[1];
else
$rowspan = 0;
// loop over the colspans
for($c = 0; $c < $colspan; $c++) {
// if the item data has not already been defined by a rowspan loop, set it
if(!isset($tableCleaned[$rowCount][$colCount]))
$tableCleaned[$rowCount][$colCount] = $item;
else
$tableCleaned[$rowCount][$colCount + 1] = $item;
// create new rowCount variable for looping through rowspans
$futureRows = $rowCount;
// loop through row spans
for($r = 1; $r < $rowspan; $r++) {
$futureRows++;
if($colspan > 1)
$tableCleaned[$futureRows][$colCount + 1] = $item;
else
$tableCleaned[$futureRows][$colCount] = $item;
}
// increase column count
$colCount++;
}
// sort the row array by the column keys (as inserting rowspans screws up the order)
ksort($tableCleaned[$rowCount]);
}
break;
}
}
// set row count
if($this->headerRow)
$this->rowCount = count($tableCleaned) - 1;
else
$this->rowCount = count($tableCleaned);
$this->rawArray = $tableCleaned;
}
/*--------------------------------------------------
--------------------------------------------------*/
function createArray() {
// define array to store table data
$tableData = array();
// get column headers
if($this->headerRow) {
// trim string
$row = $this->rawArray[$this->headerRow];
// set column names array
$columnNames = array();
$uniqueNames = array();
// loop over column names
$colCount = 0;
foreach($row as $cell) {
$colCount++;
$cell = strip_tags($cell);
$cell = trim($cell);
// save name if there is one, otherwise save index
if($cell) {
if(isset($uniqueNames[$cell])) {
$uniqueNames[$cell]++;
$cell .= ' ('.($uniqueNames[$cell] + 1).')';
}
else {
$uniqueNames[$cell] = 0;
}
$columnNames[$colCount] = $cell;
}
else
$columnNames[$colCount] = $colCount;
}
// remove the headers row from the table
unset($this->rawArray[$this->headerRow]);
}
// remove rows to drop
foreach(explode(',', $this->dropRows) as $key => $value) {
unset($this->rawArray[$value]);
}
// set the end row
if($this->maxRows)
$endRow = $this->startRow + $this->maxRows - 1;
else
$endRow = count($this->rawArray);
// loop over row array
$rowCount = 0;
$newRowCount = 0;
foreach($this->rawArray as $row) {
$rowCount++;
// if the row was requested then add it
if($rowCount >= $this->startRow && $rowCount <= $endRow) {
$newRowCount++;
// create new array to store data
$tableData[$newRowCount] = array();
//$tableData[$newRowCount]['origRow'] = $rowCount;
//$tableData[$newRowCount]['data'] = array();
$tableData[$newRowCount] = array();
// set the end column
if($this->maxCols)
$endCol = $this->startCol + $this->maxCols - 1;
else
$endCol = count($row);
// loop over cell array
$colCount = 0;
$newColCount = 0;
foreach($row as $cell) {
$colCount++;
// if the column was requested then add it
if($colCount >= $this->startCol && $colCount <= $endCol) {
$newColCount++;
if($this->extraCols) {
foreach($this->extraCols as $extraColumn) {
if($extraColumn['column'] == $colCount) {
if(preg_match($extraColumn['regex'], $cell, $matches)) {
if(is_array($extraColumn['names'])) {
$this->extraColsCount = 0;
foreach($extraColumn['names'] as $extraColumnSub) {
$this->extraColsCount++;
$tableData[$newRowCount][$extraColumnSub] = $matches[$this->extraColsCount];
}
} else {
$tableData[$newRowCount][$extraColumn['names']] = $matches[1];
}
} else {
$this->extraColsCount = 0;
if(is_array($extraColumn['names'])) {
$this->extraColsCount = 0;
foreach($extraColumn['names'] as $extraColumnSub) {
$this->extraColsCount++;
$tableData[$newRowCount][$extraColumnSub] = '';
}
} else {
$tableData[$newRowCount][$extraColumn['names']] = '';
}
}
}
}
}
if($this->stripTags)
$cell = strip_tags($cell);
// set the column key as the column number
$colKey = $newColCount;
// if there is a table header, use the column name as the key
if($this->headerRow)
if(isset($columnNames[$colCount]))
$colKey = $columnNames[$colCount];
// add the data to the array
//$tableData[$newRowCount]['data'][$colKey] = $cell;
$tableData[$newRowCount][$colKey] = $cell;
}
}
}
}
$this->finalArray = $tableData;
return $tableData;
}
}
?>