forked from samacs/simple_html_dom
-
-
Notifications
You must be signed in to change notification settings - Fork 114
/
SimpleHtmlDom.php
655 lines (573 loc) Β· 14.3 KB
/
SimpleHtmlDom.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
<?php
namespace voku\helper;
use BadMethodCallException;
use DOMElement;
use DOMNode;
use RuntimeException;
/**
* Class SimpleHtmlDom
*
* @package voku\helper
*
* @property string outerText Get dom node's outer html (alias for "outerHtml")
* @property string outerHtml Get dom node's outer html
* @property string innerText Get dom node's inner html (alias for "innerHtml")
* @property string innerHtml Get dom node's inner html
* @property-read string plaintext Get dom node's plain text
* @property-read string tag Get dom node name
* @property-read string attr Get dom node attributes
*
* @method SimpleHtmlDomNode|SimpleHtmlDom|null children() children($idx = -1) Returns children of node
* @method SimpleHtmlDom|null first_child() Returns the first child of node
* @method SimpleHtmlDom|null last_child() Returns the last child of node
* @method SimpleHtmlDom|null next_sibling() Returns the next sibling of node
* @method SimpleHtmlDom|null prev_sibling() Returns the previous sibling of node
* @method SimpleHtmlDom|null parent() Returns the parent of node
* @method string outerText() Get dom node's outer html (alias for "outerHtml()")
* @method string outerHtml() Get dom node's outer html
* @method string innerText() Get dom node's inner html (alias for "innerHtml()")
*
*/
class SimpleHtmlDom implements \IteratorAggregate
{
/**
* @var array
*/
protected static $functionAliases = array(
'children' => 'childNodes',
'first_child' => 'firstChild',
'last_child' => 'lastChild',
'next_sibling' => 'nextSibling',
'prev_sibling' => 'previousSibling',
'parent' => 'parentNode',
'outertext' => 'html',
'outerhtml' => 'html',
'innertext' => 'innerHtml',
'innerhtml' => 'innerHtml',
);
/**
* @var DOMElement
*/
protected $node;
/**
* SimpleHtmlDom constructor.
*
* @param DOMNode $node
*/
public function __construct(DOMNode $node)
{
$this->node = $node;
}
/**
* @param $name
* @param $arguments
*
* @return null|string|SimpleHtmlDom
*
*/
public function __call($name, $arguments)
{
$name = strtolower($name);
if (isset(self::$functionAliases[$name])) {
return call_user_func_array(array($this, self::$functionAliases[$name]), $arguments);
}
throw new BadMethodCallException('Method does not exist');
}
/**
* @param $name
*
* @return array|null|string
*/
public function __get($name)
{
$name = strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
return $this->html();
case 'innerhtml':
case 'innertext':
return $this->innerHtml();
case 'text':
case 'plaintext':
return $this->text();
case 'tag':
return $this->node->nodeName;
case 'attr':
return $this->getAllAttributes();
default:
return $this->getAttribute($name);
}
}
/**
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDom|SimpleHtmlDomNode|null
*/
public function __invoke($selector, $idx = null)
{
return $this->find($selector, $idx);
}
/**
* @param $name
*
* @return bool
*/
public function __isset($name)
{
switch ($name) {
case 'outertext':
case 'outerhtml':
case 'innertext':
case 'innerhtml':
case 'plaintext':
case 'text':
case 'tag':
return true;
default:
return $this->hasAttribute($name);
}
}
/**
* @param $name
* @param $value
*
* @return SimpleHtmlDom
*/
public function __set($name, $value)
{
$name = strtolower($name);
switch ($name) {
case 'outerhtml':
case 'outertext':
return $this->replaceNode($value);
case 'innertext':
case 'innerhtml':
return $this->replaceChild($value);
default:
return $this->setAttribute($name, $value);
}
}
/**
* @return string
*/
public function __toString()
{
return $this->html();
}
/**
* @param $name
*
* @return SimpleHtmlDom
*/
public function __unset($name)
{
return $this->removeAttribute($name);
}
/**
* Returns children of node
*
* @param int $idx
*
* @return SimpleHtmlDomNode|SimpleHtmlDom|null
*/
public function childNodes($idx = -1)
{
$nodeList = $this->getIterator();
if ($idx === -1) {
return $nodeList;
}
if (isset($nodeList[$idx])) {
return $nodeList[$idx];
}
return null;
}
/**
* Find list of nodes with a CSS selector
*
* @param string $selector
* @param int $idx
*
* @return SimpleHtmlDomNode|SimpleHtmlDomNode[]|SimpleHtmlDomNodeBlank
*/
public function find($selector, $idx = null)
{
return $this->getHtmlDomParser()->find($selector, $idx);
}
/**
* Returns the first child of node
*
* @return SimpleHtmlDom|null
*/
public function firstChild()
{
$node = $this->node->firstChild;
if ($node === null) {
return null;
}
return new self($node);
}
/**
* Returns array of attributes
*
* @return array|null
*/
public function getAllAttributes()
{
if ($this->node->hasAttributes()) {
$attributes = array();
foreach ($this->node->attributes as $attr) {
$attributes[$attr->name] = HtmlDomParser::putReplacedBackToPreserveHtmlEntities($attr->value);
}
return $attributes;
}
return null;
}
/**
* Return attribute value
*
* @param string $name
*
* @return string
*/
public function getAttribute($name)
{
$html = $this->node->getAttribute($name);
return HtmlDomParser::putReplacedBackToPreserveHtmlEntities($html);
}
/**
* Return SimpleHtmlDom by id.
*
* @param string $id
*
* @return SimpleHtmlDomNode|SimpleHtmlDomNode[]|SimpleHtmlDomNodeBlank
*/
public function getElementById($id)
{
return $this->find("#$id", 0);
}
/**
* Return SimpleHtmlDom by tag name.
*
* @param string $name
*
* @return SimpleHtmlDom|SimpleHtmlDomNodeBlank
*/
public function getElementByTagName($name)
{
$node = $this->node->getElementsByTagName($name)->item(0);
if ($node !== null) {
return new self($node);
} else {
return new SimpleHtmlDomNodeBlank();
}
}
/**
* Returns Elements by id
*
* @param string $id
* @param null|int $idx
*
* @return SimpleHtmlDomNode|SimpleHtmlDomNode[]|SimpleHtmlDomNodeBlank
*/
public function getElementsById($id, $idx = null)
{
return $this->find("#$id", $idx);
}
/**
* Returns Elements by tag name
*
* @param string $name
* @param null|int $idx
*
* @return SimpleHtmlDomNode|SimpleHtmlDomNode[]|SimpleHtmlDomNodeBlank
*/
public function getElementsByTagName($name, $idx = null)
{
$nodesList = $this->node->getElementsByTagName($name);
$elements = new SimpleHtmlDomNode();
foreach ($nodesList as $node) {
$elements[] = new self($node);
}
if (null === $idx) {
return $elements;
} else {
if ($idx < 0) {
$idx = count($elements) + $idx;
}
}
if (isset($elements[$idx])) {
return $elements[$idx];
} else {
return new SimpleHtmlDomNodeBlank();
}
}
/**
* Create a new "HtmlDomParser"-object from the current context.
*
* @return HtmlDomParser
*/
public function getHtmlDomParser()
{
return new HtmlDomParser($this);
}
/**
* Retrieve an external iterator
*
* @link http://php.net/manual/en/iteratoraggregate.getiterator.php
* @return SimpleHtmlDomNode An instance of an object implementing <b>Iterator</b> or
* <b>Traversable</b>
*/
public function getIterator()
{
$elements = new SimpleHtmlDomNode();
if ($this->node->hasChildNodes()) {
foreach ($this->node->childNodes as $node) {
$elements[] = new self($node);
}
}
return $elements;
}
/**
* @return DOMNode
*/
public function getNode()
{
return $this->node;
}
/**
* Determine if an attribute exists on the element.
*
* @param $name
*
* @return bool
*/
public function hasAttribute($name)
{
return $this->node->hasAttribute($name);
}
/**
* Get dom node's outer html
*
* @return string
*/
public function html()
{
return $this->getHtmlDomParser()->html();
}
/**
* Get dom node's inner html
*
* @return string
*/
public function innerHtml()
{
return $this->getHtmlDomParser()->innerHtml();
}
/**
* Returns the last child of node
*
* @return SimpleHtmlDom|null
*/
public function lastChild()
{
$node = $this->node->lastChild;
if ($node === null) {
return null;
}
return new self($node);
}
/**
* Returns the next sibling of node
*
* @return SimpleHtmlDom|null
*/
public function nextSibling()
{
$node = $this->node->nextSibling;
if ($node === null) {
return null;
}
return new self($node);
}
/**
* Returns the parent of node
*
* @return SimpleHtmlDom
*/
public function parentNode()
{
return new self($this->node->parentNode);
}
/**
* Returns the previous sibling of node
*
* @return SimpleHtmlDom|null
*/
public function previousSibling()
{
$node = $this->node->previousSibling;
if ($node === null) {
return null;
}
return new self($node);
}
/**
* Replace child node
*
* @param $string
*
* @return $this
*/
protected function replaceChild($string)
{
if (!empty($string)) {
$newDocument = new HtmlDomParser($string);
if ($this->normalizeStringForComparision($newDocument->outertext) != $this->normalizeStringForComparision($string)) {
throw new RuntimeException('Not valid HTML fragment');
}
}
/** @noinspection PhpParamsInspection */
if (count($this->node->childNodes) > 0) {
foreach ($this->node->childNodes as $node) {
$this->node->removeChild($node);
}
}
if (!empty($newDocument)) {
$newDocument = $this->cleanHtmlWrapper($newDocument);
$newNode = $this->node->ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
$this->node->appendChild($newNode);
}
return $this;
}
/**
* Replace this node
*
* @param $string
*
* @return $this
*/
protected function replaceNode($string)
{
if (empty($string)) {
$this->node->parentNode->removeChild($this->node);
return null;
}
$newDocument = new HtmlDomParser($string);
if ($this->normalizeStringForComparision($newDocument->outertext) != $this->normalizeStringForComparision($string)) {
throw new RuntimeException('Not valid HTML fragment');
}
$newDocument = $this->cleanHtmlWrapper($newDocument);
$newNode = $this->node->ownerDocument->importNode($newDocument->getDocument()->documentElement, true);
$this->node->parentNode->replaceChild($newNode, $this->node);
$this->node = $newNode;
return $this;
}
/**
* Normalize the given string for comparision.
*
* @param $string
*
* @return string
*/
private function normalizeStringForComparision($string)
{
return urlencode(urldecode(trim(str_replace(array(' ', "\n", "\r\n", "\r"), '', strtolower($string)))));
}
/**
* @param HtmlDomParser $newDocument
*
* @return HtmlDomParser
*/
protected function cleanHtmlWrapper(HtmlDomParser $newDocument)
{
if ($newDocument->getIsDOMDocumentCreatedWithoutHtml() === true) {
// Remove doc-type node.
$newDocument->getDocument()->doctype->parentNode->removeChild($newDocument->getDocument()->doctype);
// Remove html element, preserving child nodes.
$html = $newDocument->getDocument()->getElementsByTagName('html')->item(0);
$fragment = $newDocument->getDocument()->createDocumentFragment();
while ($html->childNodes->length > 0) {
$fragment->appendChild($html->childNodes->item(0));
}
$html->parentNode->replaceChild($fragment, $html);
// Remove body element, preserving child nodes.
$body = $newDocument->getDocument()->getElementsByTagName('body')->item(0);
$fragment = $newDocument->getDocument()->createDocumentFragment();
while ($body->childNodes->length > 0) {
$fragment->appendChild($body->childNodes->item(0));
}
$body->parentNode->replaceChild($fragment, $body);
// At this point DOMDocument still added a "<p>"-wrapper around our string,
// so we replace it with "<simpleHtmlDomP>" and delete this at the ending ...
$this->changeElementName($newDocument->getDocument()->getElementsByTagName('p')->item(0), 'simpleHtmlDomP');
}
return $newDocument;
}
/**
* change the name of a tag in a "DOMNode"
*
* @param DOMNode $node
* @param string $name
*
* @return DOMElement
*/
protected function changeElementName(\DOMNode $node, $name)
{
$newnode = $node->ownerDocument->createElement($name);
foreach ($node->childNodes as $child) {
$child = $node->ownerDocument->importNode($child, true);
$newnode->appendChild($child);
}
foreach ($node->attributes as $attrName => $attrNode) {
$newnode->setAttribute($attrName, $attrNode);
}
$newnode->ownerDocument->replaceChild($newnode, $node);
return $newnode;
}
/**
* Set attribute value
*
* @param string $name
* @param string|null $value Set to NULL or empty string, to remove the attribute.
* @param bool $strict $value must be NULL, to remove the attribute,
* so that you can set an empty string as attribute-value e.g. autofocus=""
*
* @return $this
*/
public function setAttribute($name, $value = null, $strict = false)
{
if (
($strict === true && null === $value)
||
($strict === false && empty($value))
) {
$this->node->removeAttribute($name);
} else {
$this->node->setAttribute($name, $value);
}
return $this;
}
/**
* Remove attribute
*
* @param $name
*
* @return mixed
*/
public function removeAttribute($name)
{
$this->node->removeAttribute($name);
return $this;
}
/**
* Get dom node's plain text
*
* @return string
*/
public function text()
{
return $this->node->textContent;
}
}