forked from bupt1987/html-parser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathParserDom.php
More file actions
420 lines (398 loc) · 9.09 KB
/
ParserDom.php
File metadata and controls
420 lines (398 loc) · 9.09 KB
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
<?php
namespace HtmlParser;
/**
* Copyright (c) 2013, 俊杰Jerry
* All rights reserved.
*
* @description: html解析器
* @author : 俊杰Jerry<bupt1987@gmail.com>
* @date : 2013-6-10
*/
class ParserDom {
/**
* @var \DOMNode
*/
public $node;
/**
* @var array
*/
private $_lFind = array();
/**
* @param \DOMNode|string $node
* @throws \Exception
*/
public function __construct($node = null) {
if ($node !== null) {
if ($node instanceof \DOMNode) {
$this->node = $node;
} else {
$dom = new \DOMDocument();
$dom->preserveWhiteSpace = false;
$dom->strictErrorChecking = false;
if (@$dom->loadHTML($node)) {
$this->node = $dom;
} else {
throw new \Exception('load html error');
}
}
}
}
/**
* @codeCoverageIgnore
*/
public function __destruct() {
$this->clearNode($this->node);
}
/**
* 广度优先查询
*
* @param string $selector
* @param number $idx 找第几个,从0开始计算,null 表示都返回, 负数表示倒数第几个
* @return ParserDom|ParserDom[]
*/
/*public function findBreadthFirst($selector, $idx = null) {
if (empty($this->node->childNodes)) {
return false;
}
$selectors = $this->parse_selector($selector);
if (($count = count($selectors)) === 0) {
return false;
}
$found = array();
for ($c = 0; $c < $count; $c++) {
if (($level = count($selectors [$c])) === 0) {
return false;
}
$need_to_search = iterator_to_array($this->node->childNodes);
$search_level = 1;
while (!empty($need_to_search)) {
$temp = array();
foreach ($need_to_search as $search) {
if ($search_level >= $level) {
$rs = $this->seek($search, $selectors [$c], $level - 1);
if ($rs !== false && $idx !== null) {
if ($idx == count($found)) {
return new self($rs);
} else {
$found[] = new self($rs);
}
} elseif ($rs !== false) {
$found[] = new self($rs);
}
}
$temp[] = $search;
array_shift($need_to_search);
}
foreach ($temp as $temp_val) {
if (!empty($temp_val->childNodes)) {
foreach ($temp_val->childNodes as $val) {
$need_to_search[] = $val;
}
}
}
$search_level++;
}
}
if ($idx !== null) {
if ($idx < 0) {
$idx = count($found) + $idx;
}
if (isset($found[$idx])) {
return $found[$idx];
} else {
return false;
}
}
return $found;
}*/
/**
* 深度优先查询
*
* @param string $selector
* @param number $idx 找第几个,从0开始计算,null 表示都返回, 负数表示倒数第几个
* @return self|self[]
*/
public function find($selector, $idx = null) {
if (empty($this->node->childNodes)) {
return false;
}
$selectors = $this->parse_selector($selector);
if (($count = count($selectors)) === 0) {
return false;
}
for ($c = 0; $c < $count; $c++) {
if (($level = count($selectors [$c])) === 0) {
return false;
}
$this->search($this->node, $idx, $selectors [$c], $level);
}
$found = $this->_lFind;
$this->_lFind = array();
if ($idx !== null) {
if ($idx < 0) {
$idx = count($found) + $idx;
}
if (isset($found[$idx])) {
return $found[$idx];
} else {
return false;
}
}
return $found;
}
/**
* 返回文本信息
*
* @return string
*/
public function getPlainText() {
return $this->text($this->node);
}
/**
* 获取innerHtml
* @return string
*/
public function innerHtml() {
$innerHTML = "";
$children = $this->node->childNodes;
foreach ($children as $child) {
$innerHTML .= $this->node->ownerDocument->saveHTML($child) ?: '';
}
return $innerHTML;
}
/**
* 获取outerHtml
* @return string|bool
*/
public function outerHtml() {
$doc = new \DOMDocument();
$doc->appendChild($doc->importNode($this->node, true));
return $doc->saveHTML($doc);
}
/**
* 获取html的元属值
*
* @param string $name
* @return string|null
*/
public function getAttr($name) {
$oAttr = $this->node->attributes->getNamedItem($name);
if (isset($oAttr)) {
return $oAttr->nodeValue;
}
return null;
}
/**
* 匹配
*
* @param string $exp
* @param string $pattern
* @param string $value
* @return boolean|number
*/
private function match($exp, $pattern, $value) {
$pattern = strtolower($pattern);
$value = strtolower($value);
switch ($exp) {
case '=' :
return ($value === $pattern);
case '!=' :
return ($value !== $pattern);
case '^=' :
return preg_match("/^" . preg_quote($pattern, '/') . "/", $value);
case '$=' :
return preg_match("/" . preg_quote($pattern, '/') . "$/", $value);
case '*=' :
if ($pattern [0] == '/') {
return preg_match($pattern, $value);
}
return preg_match("/" . $pattern . "/i", $value);
}
return false;
}
/**
* 分析查询语句
*
* @param string $selector_string
* @return array
*/
private function parse_selector($selector_string) {
$pattern = '/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)["\']?(.*?)["\']?)?\])?([\/, ]+)/is';
preg_match_all($pattern, trim($selector_string) . ' ', $matches, PREG_SET_ORDER);
$selectors = array();
$result = array();
foreach ($matches as $m) {
$m [0] = trim($m [0]);
if ($m [0] === '' || $m [0] === '/' || $m [0] === '//')
continue;
if ($m [1] === 'tbody')
continue;
list ($tag, $key, $val, $exp, $no_key) = array($m [1], null, null, '=', false);
if (!empty ($m [2])) {
$key = 'id';
$val = $m [2];
}
if (!empty ($m [3])) {
$key = 'class';
$val = $m [3];
}
if (!empty ($m [4])) {
$key = $m [4];
}
if (!empty ($m [5])) {
$exp = $m [5];
}
if (!empty ($m [6])) {
$val = $m [6];
}
// convert to lowercase
$tag = strtolower($tag);
$key = strtolower($key);
// elements that do NOT have the specified attribute
if (isset ($key [0]) && $key [0] === '!') {
$key = substr($key, 1);
$no_key = true;
}
$result [] = array($tag, $key, $val, $exp, $no_key);
if (trim($m [7]) === ',') {
$selectors [] = $result;
$result = array();
}
}
if (count($result) > 0) {
$selectors [] = $result;
}
return $selectors;
}
/**
* 深度查询
*
* @param \DOMNode $search
* @param $idx
* @param $selectors
* @param $level
* @param int $search_level
* @return bool
*/
private function search(&$search, $idx, $selectors, $level, $search_level = 0) {
if ($search_level >= $level) {
$rs = $this->seek($search, $selectors, $level - 1);
if ($rs !== false && $idx !== null) {
if ($idx == count($this->_lFind)) {
$this->_lFind[] = new self($rs);
return true;
} else {
$this->_lFind[] = new self($rs);
}
} elseif ($rs !== false) {
$this->_lFind[] = new self($rs);
}
}
if (!empty($search->childNodes)) {
foreach ($search->childNodes as $val) {
if ($this->search($val, $idx, $selectors, $level, $search_level + 1)) {
return true;
}
}
}
return false;
}
/**
* 获取tidy_node文本
*
* @param \DOMNode $node
* @return string
*/
private function text(&$node) {
return $node->textContent;
}
/**
* 匹配节点,由于采取的倒序查找,所以时间复杂度为n+m*l n为总节点数,m为匹配最后一个规则的个数,l为规则的深度,
* @codeCoverageIgnore
* @param \DOMNode $search
* @param array $selectors
* @param int $current
* @return boolean|\DOMNode
*/
private function seek($search, $selectors, $current) {
if (!($search instanceof \DOMElement)) {
return false;
}
list ($tag, $key, $val, $exp, $no_key) = $selectors [$current];
$pass = true;
if ($tag === '*' && !$key) {
exit('tag为*时,key不能为空');
}
if ($tag && $tag != $search->tagName && $tag !== '*') {
$pass = false;
}
if ($pass && $key) {
if ($no_key) {
if ($search->hasAttribute($key)) {
$pass = false;
}
} else {
if ($key != "plaintext" && !$search->hasAttribute($key)) {
$pass = false;
}
}
}
if ($pass && $key && $val && $val !== '*') {
if ($key == "plaintext") {
$nodeKeyValue = $this->text($search);
} else {
$nodeKeyValue = $search->getAttribute($key);
}
$check = $this->match($exp, $val, $nodeKeyValue);
if (!$check && strcasecmp($key, 'class') === 0) {
foreach (explode(' ', $search->getAttribute($key)) as $k) {
if (!empty ($k)) {
$check = $this->match($exp, $val, $k);
if ($check) {
break;
}
}
}
}
if (!$check) {
$pass = false;
}
}
if ($pass) {
$current--;
if ($current < 0) {
return $search;
} elseif ($this->seek($this->getParent($search), $selectors, $current)) {
return $search;
} else {
return false;
}
} else {
return false;
}
}
/**
* 获取父亲节点
*
* @param \DOMNode $node
* @return \DOMNode
*/
private function getParent($node) {
return $node->parentNode;
}
/**
* @codeCoverageIgnore
* 释放内存
*
* @param $node
*/
private function clearNode(&$node) {
if (!empty($node->childNodes)) {
foreach ($node->childNodes as $child) {
$this->clearNode($child);
}
}
unset($node);
}
}
?>