├── README.md ├── Src └── Sunra │ └── PhpSimple │ ├── HtmlDomParser.php │ └── simplehtmldom_1_5 │ └── simple_html_dom.php └── composer.json /README.md: -------------------------------------------------------------------------------- 1 | php-simple-html-dom-parser 2 | ========================== 3 | 4 | Version 1.5.2 5 | 6 | Adaptation for Composer and PSR-0 of: 7 | 8 | A HTML DOM parser written in PHP5+ let you manipulate HTML in a very easy way! 9 | Require PHP 5+. 10 | Supports invalid HTML. 11 | Find tags on an HTML page with selectors just like jQuery. 12 | Extract contents from HTML in a single line. 13 | 14 | http://simplehtmldom.sourceforge.net/ 15 | 16 | 17 | Install 18 | ------- 19 | 20 | composer.phar 21 | ```json 22 | "require": { 23 | "sunra/php-simple-html-dom-parser": "1.5.2" 24 | } 25 | ``` 26 | 27 | Usage 28 | ----- 29 | 30 | ```php 31 | use Sunra\PhpSimple\HtmlDomParser; 32 | 33 | ... 34 | $dom = HtmlDomParser::str_get_html( $str ); 35 | or 36 | $dom = HtmlDomParser::file_get_html( $file_name ); 37 | 38 | $elems = $dom->find($elem_name); 39 | ... 40 | 41 | ``` 42 | -------------------------------------------------------------------------------- /Src/Sunra/PhpSimple/HtmlDomParser.php: -------------------------------------------------------------------------------- 1 | size is the "real" number of bytes the dom was created from. 20 | * but for most purposes, it's a really good estimation. 21 | * Paperg - Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors. 22 | * Allow the user to tell us how much they trust the html. 23 | * Paperg add the text and plaintext to the selectors for the find syntax. plaintext implies text in the innertext of a node. text implies that the tag is a text node. 24 | * This allows for us to find tags based on the text they contain. 25 | * Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag. 26 | * Paperg: added parse_charset so that we know about the character set of the source document. 27 | * NOTE: If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the 28 | * last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection. 29 | * 30 | * Found infinite loop in the case of broken html in restore_noise. Rewrote to protect from that. 31 | * PaperG (John Schlick) Added get_display_size for "IMG" tags. 32 | * 33 | * Licensed under The MIT License 34 | * Redistributions of files must retain the above copyright notice. 35 | * 36 | * @author S.C. Chen 37 | * @author John Schlick 38 | * @author Rus Carroll 39 | * @version 1.5 ($Rev: 196 $) 40 | * @package PlaceLocalInclude 41 | * @subpackage simple_html_dom 42 | */ 43 | 44 | /** 45 | * All of the Defines for the classes below. 46 | * @author S.C. Chen 47 | */ 48 | define('HDOM_TYPE_ELEMENT', 1); 49 | define('HDOM_TYPE_COMMENT', 2); 50 | define('HDOM_TYPE_TEXT', 3); 51 | define('HDOM_TYPE_ENDTAG', 4); 52 | define('HDOM_TYPE_ROOT', 5); 53 | define('HDOM_TYPE_UNKNOWN', 6); 54 | define('HDOM_QUOTE_DOUBLE', 0); 55 | define('HDOM_QUOTE_SINGLE', 1); 56 | define('HDOM_QUOTE_NO', 3); 57 | define('HDOM_INFO_BEGIN', 0); 58 | define('HDOM_INFO_END', 1); 59 | define('HDOM_INFO_QUOTE', 2); 60 | define('HDOM_INFO_SPACE', 3); 61 | define('HDOM_INFO_TEXT', 4); 62 | define('HDOM_INFO_INNER', 5); 63 | define('HDOM_INFO_OUTER', 6); 64 | define('HDOM_INFO_ENDSPACE',7); 65 | define('DEFAULT_TARGET_CHARSET', 'UTF-8'); 66 | define('DEFAULT_BR_TEXT', "\r\n"); 67 | define('DEFAULT_SPAN_TEXT', " "); 68 | if (!defined('MAX_FILE_SIZE')) 69 | { 70 | define('MAX_FILE_SIZE', 600000); 71 | } 72 | // helper functions 73 | // ----------------------------------------------------------------------------- 74 | // get html dom from file 75 | // $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1. 76 | function file_get_html($url, $use_include_path = false, $context=null, $offset=0, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 77 | { 78 | // We DO force the tags to be terminated. 79 | $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText); 80 | // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done. 81 | $contents = file_get_contents($url, $use_include_path, $context, $offset); 82 | // Paperg - use our own mechanism for getting the contents as we want to control the timeout. 83 | //$contents = retrieve_url_contents($url); 84 | if (empty($contents) || strlen($contents) > MAX_FILE_SIZE) 85 | { 86 | return false; 87 | } 88 | // The second parameter can force the selectors to all be lowercase. 89 | $dom->load($contents, $lowercase, $stripRN); 90 | return $dom; 91 | } 92 | 93 | // get html dom from string 94 | function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 95 | { 96 | $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText); 97 | if (empty($str) || strlen($str) > MAX_FILE_SIZE) 98 | { 99 | $dom->clear(); 100 | return false; 101 | } 102 | $dom->load($str, $lowercase, $stripRN); 103 | return $dom; 104 | } 105 | 106 | // dump html dom tree 107 | function dump_html_tree($node, $show_attr=true, $deep=0) 108 | { 109 | $node->dump($node); 110 | } 111 | 112 | 113 | /** 114 | * simple html dom node 115 | * PaperG - added ability for "find" routine to lowercase the value of the selector. 116 | * PaperG - added $tag_start to track the start position of the tag in the total byte index 117 | * 118 | * @package PlaceLocalInclude 119 | */ 120 | class simple_html_dom_node 121 | { 122 | public $nodetype = HDOM_TYPE_TEXT; 123 | public $tag = 'text'; 124 | public $attr = array(); 125 | /** @var simple_html_dom_node[] $children */ 126 | public $children = array(); 127 | public $nodes = array(); 128 | public $parent = null; 129 | // The "info" array - see HDOM_INFO_... for what each element contains. 130 | public $_ = array(); 131 | public $tag_start = 0; 132 | private $dom = null; 133 | 134 | function __construct(simple_html_dom $dom) 135 | { 136 | $this->dom = $dom; 137 | $dom->nodes[] = $this; 138 | } 139 | 140 | function __destruct() 141 | { 142 | $this->clear(); 143 | } 144 | 145 | function __toString() 146 | { 147 | return $this->outertext(); 148 | } 149 | 150 | // clean up memory due to php5 circular references memory leak... 151 | function clear() 152 | { 153 | $this->dom = null; 154 | $this->nodes = null; 155 | $this->parent = null; 156 | $this->children = null; 157 | } 158 | 159 | // dump node's tree 160 | function dump($show_attr=true, $deep=0) 161 | { 162 | $lead = str_repeat(' ', $deep); 163 | 164 | echo $lead.$this->tag; 165 | if ($show_attr && count($this->attr)>0) 166 | { 167 | echo '('; 168 | foreach ($this->attr as $k=>$v) 169 | echo "[$k]=>\"".$this->$k.'", '; 170 | echo ')'; 171 | } 172 | echo "\n"; 173 | 174 | if ($this->nodes) 175 | { 176 | foreach ($this->nodes as $c) 177 | { 178 | $c->dump($show_attr, $deep+1); 179 | } 180 | } 181 | } 182 | 183 | 184 | // Debugging function to dump a single dom node with a bunch of information about it. 185 | function dump_node($echo=true) 186 | { 187 | 188 | $string = $this->tag; 189 | if (count($this->attr)>0) 190 | { 191 | $string .= '('; 192 | foreach ($this->attr as $k=>$v) 193 | { 194 | $string .= "[$k]=>\"".$this->$k.'", '; 195 | } 196 | $string .= ')'; 197 | } 198 | if (count($this->_)>0) 199 | { 200 | $string .= ' $_ ('; 201 | foreach ($this->_ as $k=>$v) 202 | { 203 | if (is_array($v)) 204 | { 205 | $string .= "[$k]=>("; 206 | foreach ($v as $k2=>$v2) 207 | { 208 | $string .= "[$k2]=>\"".$v2.'", '; 209 | } 210 | $string .= ")"; 211 | } else { 212 | $string .= "[$k]=>\"".$v.'", '; 213 | } 214 | } 215 | $string .= ")"; 216 | } 217 | 218 | if (isset($this->text)) 219 | { 220 | $string .= " text: (" . $this->text . ")"; 221 | } 222 | 223 | $string .= " HDOM_INNER_INFO: '"; 224 | if (isset($node->_[HDOM_INFO_INNER])) 225 | { 226 | $string .= $node->_[HDOM_INFO_INNER] . "'"; 227 | } 228 | else 229 | { 230 | $string .= ' NULL '; 231 | } 232 | 233 | $string .= " children: " . count($this->children); 234 | $string .= " nodes: " . count($this->nodes); 235 | $string .= " tag_start: " . $this->tag_start; 236 | $string .= "\n"; 237 | 238 | if ($echo) 239 | { 240 | echo $string; 241 | return; 242 | } 243 | else 244 | { 245 | return $string; 246 | } 247 | } 248 | 249 | // returns the parent of node 250 | // If a node is passed in, it will reset the parent of the current node to that one. 251 | function parent($parent=null) 252 | { 253 | // I am SURE that this doesn't work properly. 254 | // It fails to unset the current node from it's current parents nodes or children list first. 255 | if ($parent !== null) 256 | { 257 | $this->parent = $parent; 258 | $this->parent->nodes[] = $this; 259 | $this->parent->children[] = $this; 260 | } 261 | 262 | return $this->parent; 263 | } 264 | 265 | // verify that node has children 266 | function has_child() 267 | { 268 | return !empty($this->children); 269 | } 270 | 271 | // returns children of node 272 | function children($idx=-1) 273 | { 274 | if ($idx===-1) 275 | { 276 | return $this->children; 277 | } 278 | if (isset($this->children[$idx])) return $this->children[$idx]; 279 | return null; 280 | } 281 | 282 | // returns the first child of node 283 | function first_child() 284 | { 285 | if (count($this->children)>0) 286 | { 287 | return $this->children[0]; 288 | } 289 | return null; 290 | } 291 | 292 | // returns the last child of node 293 | function last_child() 294 | { 295 | if (($count=count($this->children))>0) 296 | { 297 | return $this->children[$count-1]; 298 | } 299 | return null; 300 | } 301 | 302 | // returns the next sibling of node 303 | function next_sibling() 304 | { 305 | if ($this->parent===null) 306 | { 307 | return null; 308 | } 309 | 310 | $idx = 0; 311 | $count = count($this->parent->children); 312 | while ($idx<$count && $this!==$this->parent->children[$idx]) 313 | { 314 | ++$idx; 315 | } 316 | if (++$idx>=$count) 317 | { 318 | return null; 319 | } 320 | return $this->parent->children[$idx]; 321 | } 322 | 323 | // returns the previous sibling of node 324 | function prev_sibling() 325 | { 326 | if ($this->parent===null) return null; 327 | $idx = 0; 328 | $count = count($this->parent->children); 329 | while ($idx<$count && $this!==$this->parent->children[$idx]) 330 | ++$idx; 331 | if (--$idx<0) return null; 332 | return $this->parent->children[$idx]; 333 | } 334 | 335 | // function to locate a specific ancestor tag in the path to the root. 336 | function find_ancestor_tag($tag) 337 | { 338 | global $debugObject; 339 | if (is_object($debugObject)) { $debugObject->debugLogEntry(1); } 340 | 341 | // Start by including ourselves in the comparison. 342 | $returnDom = $this; 343 | 344 | while (!is_null($returnDom)) 345 | { 346 | if (is_object($debugObject)) { $debugObject->debugLog(2, "Current tag is: " . $returnDom->tag); } 347 | 348 | if ($returnDom->tag == $tag) 349 | { 350 | break; 351 | } 352 | $returnDom = $returnDom->parent; 353 | } 354 | return $returnDom; 355 | } 356 | 357 | // get dom node's inner html 358 | function innertext() 359 | { 360 | if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; 361 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 362 | 363 | $ret = ''; 364 | foreach ($this->nodes as $n) 365 | $ret .= $n->outertext(); 366 | return $ret; 367 | } 368 | 369 | // get dom node's outer text (with tag) 370 | function outertext() 371 | { 372 | global $debugObject; 373 | if (is_object($debugObject)) 374 | { 375 | $text = ''; 376 | if ($this->tag == 'text') 377 | { 378 | if (!empty($this->text)) 379 | { 380 | $text = " with text: " . $this->text; 381 | } 382 | } 383 | $debugObject->debugLog(1, 'Innertext of tag: ' . $this->tag . $text); 384 | } 385 | 386 | if ($this->tag==='root') return $this->innertext(); 387 | 388 | // trigger callback 389 | if ($this->dom && $this->dom->callback!==null) 390 | { 391 | call_user_func_array($this->dom->callback, array($this)); 392 | } 393 | 394 | if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER]; 395 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 396 | 397 | // render begin tag 398 | if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]) 399 | { 400 | $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup(); 401 | } else { 402 | $ret = ""; 403 | } 404 | 405 | // render inner text 406 | if (isset($this->_[HDOM_INFO_INNER])) 407 | { 408 | // If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added. 409 | if ($this->tag != "br") 410 | { 411 | $ret .= $this->_[HDOM_INFO_INNER]; 412 | } 413 | } else { 414 | if ($this->nodes) 415 | { 416 | foreach ($this->nodes as $n) 417 | { 418 | $ret .= $this->convert_text($n->outertext()); 419 | } 420 | } 421 | } 422 | 423 | // render end tag 424 | if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0) 425 | $ret .= 'tag.'>'; 426 | return $ret; 427 | } 428 | 429 | // get dom node's plain text 430 | function text() 431 | { 432 | if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; 433 | switch ($this->nodetype) 434 | { 435 | case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 436 | case HDOM_TYPE_COMMENT: return ''; 437 | case HDOM_TYPE_UNKNOWN: return ''; 438 | } 439 | if (strcasecmp($this->tag, 'script')===0) return ''; 440 | if (strcasecmp($this->tag, 'style')===0) return ''; 441 | 442 | $ret = ''; 443 | // In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL. 444 | // NOTE: This indicates that there is a problem where it's set to NULL without a clear happening. 445 | // WHY is this happening? 446 | if (!is_null($this->nodes)) 447 | { 448 | foreach ($this->nodes as $n) 449 | { 450 | $ret .= $this->convert_text($n->text()); 451 | } 452 | 453 | // If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all. 454 | if ($this->tag == "span") 455 | { 456 | $ret .= $this->dom->default_span_text; 457 | } 458 | 459 | 460 | } 461 | return $ret; 462 | } 463 | 464 | function xmltext() 465 | { 466 | $ret = $this->innertext(); 467 | $ret = str_ireplace('', '', $ret); 469 | return $ret; 470 | } 471 | 472 | // build node's text with tag 473 | function makeup() 474 | { 475 | // text, comment, unknown 476 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 477 | 478 | $ret = '<'.$this->tag; 479 | $i = -1; 480 | 481 | foreach ($this->attr as $key=>$val) 482 | { 483 | ++$i; 484 | 485 | // skip removed attribute 486 | if ($val===null || $val===false) 487 | continue; 488 | 489 | $ret .= $this->_[HDOM_INFO_SPACE][$i][0]; 490 | //no value attr: nowrap, checked selected... 491 | if ($val===true) 492 | $ret .= $key; 493 | else { 494 | switch ($this->_[HDOM_INFO_QUOTE][$i]) 495 | { 496 | case HDOM_QUOTE_DOUBLE: $quote = '"'; break; 497 | case HDOM_QUOTE_SINGLE: $quote = '\''; break; 498 | default: $quote = ''; 499 | } 500 | $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote; 501 | } 502 | } 503 | $ret = $this->dom->restore_noise($ret); 504 | return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>'; 505 | } 506 | 507 | /** 508 | * find elements by css selector 509 | * PaperG - added ability for find to lowercase the value of the selector. 510 | * @param string $selector 511 | * @param int|null $idx 512 | * @param bool $lowercase 513 | * @return simple_html_dom_node[]|simple_html_dom_node|null 514 | */ 515 | function find($selector, $idx=null, $lowercase=false) 516 | { 517 | $selectors = $this->parse_selector($selector); 518 | if (($count=count($selectors))===0) return array(); 519 | $found_keys = array(); 520 | 521 | // find each selector 522 | for ($c=0; $c<$count; ++$c) 523 | { 524 | // The change on the below line was documented on the sourceforge code tracker id 2788009 525 | // used to be: if (($levle=count($selectors[0]))===0) return array(); 526 | if (($levle=count($selectors[$c]))===0) return array(); 527 | if (!isset($this->_[HDOM_INFO_BEGIN])) return array(); 528 | 529 | $head = array($this->_[HDOM_INFO_BEGIN]=>1); 530 | 531 | // handle descendant selectors, no recursive! 532 | for ($l=0; $l<$levle; ++$l) 533 | { 534 | $ret = array(); 535 | foreach ($head as $k=>$v) 536 | { 537 | $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k]; 538 | //PaperG - Pass this optional parameter on to the seek function. 539 | $n->seek($selectors[$c][$l], $ret, $lowercase); 540 | } 541 | $head = $ret; 542 | } 543 | 544 | foreach ($head as $k=>$v) 545 | { 546 | if (!isset($found_keys[$k])) 547 | $found_keys[$k] = 1; 548 | } 549 | } 550 | 551 | // sort keys 552 | ksort($found_keys); 553 | 554 | $found = array(); 555 | foreach ($found_keys as $k=>$v) 556 | $found[] = $this->dom->nodes[$k]; 557 | 558 | // return nth-element or array 559 | if (is_null($idx)) return $found; 560 | else if ($idx<0) $idx = count($found) + $idx; 561 | return (isset($found[$idx])) ? $found[$idx] : null; 562 | } 563 | 564 | // seek for given conditions 565 | // PaperG - added parameter to allow for case insensitive testing of the value of a selector. 566 | protected function seek($selector, &$ret, $lowercase=false) 567 | { 568 | global $debugObject; 569 | if (is_object($debugObject)) { $debugObject->debugLogEntry(1); } 570 | 571 | list($tag, $key, $val, $exp, $no_key) = $selector; 572 | 573 | // xpath index 574 | if ($tag && $key && is_numeric($key)) 575 | { 576 | $count = 0; 577 | foreach ($this->children as $c) 578 | { 579 | if ($tag==='*' || $tag===$c->tag) { 580 | if (++$count==$key) { 581 | $ret[$c->_[HDOM_INFO_BEGIN]] = 1; 582 | return; 583 | } 584 | } 585 | } 586 | return; 587 | } 588 | 589 | $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0; 590 | if ($end==0) { 591 | $parent = $this->parent; 592 | while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) { 593 | $end -= 1; 594 | $parent = $parent->parent; 595 | } 596 | $end += $parent->_[HDOM_INFO_END]; 597 | } 598 | 599 | for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) { 600 | $node = $this->dom->nodes[$i]; 601 | 602 | $pass = true; 603 | 604 | if ($tag==='*' && !$key) { 605 | if (in_array($node, $this->children, true)) 606 | $ret[$i] = 1; 607 | continue; 608 | } 609 | 610 | // compare tag 611 | if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;} 612 | // compare key 613 | if ($pass && $key) { 614 | if ($no_key) { 615 | if (isset($node->attr[$key])) $pass=false; 616 | } else { 617 | if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false; 618 | } 619 | } 620 | // compare value 621 | if ($pass && $key && $val && $val!=='*') { 622 | // If they have told us that this is a "plaintext" search then we want the plaintext of the node - right? 623 | if ($key == "plaintext") { 624 | // $node->plaintext actually returns $node->text(); 625 | $nodeKeyValue = $node->text(); 626 | } else { 627 | // this is a normal search, we want the value of that attribute of the tag. 628 | $nodeKeyValue = $node->attr[$key]; 629 | } 630 | if (is_object($debugObject)) {$debugObject->debugLog(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);} 631 | 632 | //PaperG - If lowercase is set, do a case insensitive test of the value of the selector. 633 | if ($lowercase) { 634 | $check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue)); 635 | } else { 636 | $check = $this->match($exp, $val, $nodeKeyValue); 637 | } 638 | if (is_object($debugObject)) {$debugObject->debugLog(2, "after match: " . ($check ? "true" : "false"));} 639 | 640 | // handle multiple class 641 | if (!$check && strcasecmp($key, 'class')===0) { 642 | foreach (explode(' ',$node->attr[$key]) as $k) { 643 | // Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form. 644 | if (!empty($k)) { 645 | if ($lowercase) { 646 | $check = $this->match($exp, strtolower($val), strtolower($k)); 647 | } else { 648 | $check = $this->match($exp, $val, $k); 649 | } 650 | if ($check) break; 651 | } 652 | } 653 | } 654 | if (!$check) $pass = false; 655 | } 656 | if ($pass) $ret[$i] = 1; 657 | unset($node); 658 | } 659 | // It's passed by reference so this is actually what this function returns. 660 | if (is_object($debugObject)) {$debugObject->debugLog(1, "EXIT - ret: ", $ret);} 661 | } 662 | 663 | protected function match($exp, $pattern, $value) { 664 | global $debugObject; 665 | if (is_object($debugObject)) {$debugObject->debugLogEntry(1);} 666 | 667 | switch ($exp) { 668 | case '=': 669 | return ($value===$pattern); 670 | case '!=': 671 | return ($value!==$pattern); 672 | case '^=': 673 | return preg_match("/^".preg_quote($pattern,'/')."/", $value); 674 | case '$=': 675 | return preg_match("/".preg_quote($pattern,'/')."$/", $value); 676 | case '*=': 677 | if ($pattern[0]=='/') { 678 | return preg_match($pattern, $value); 679 | } 680 | return preg_match("/".$pattern."/i", $value); 681 | } 682 | return false; 683 | } 684 | 685 | protected function parse_selector($selector_string) { 686 | global $debugObject; 687 | if (is_object($debugObject)) {$debugObject->debugLogEntry(1);} 688 | 689 | // pattern of CSS selectors, modified from mootools 690 | // Paperg: Add the colon to the attrbute, so that it properly finds like google does. 691 | // Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check. 692 | // Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured. 693 | // This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression. 694 | // farther study is required to determine of this should be documented or removed. 695 | // $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; 696 | $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; 697 | preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER); 698 | if (is_object($debugObject)) {$debugObject->debugLog(2, "Matches Array: ", $matches);} 699 | 700 | $selectors = array(); 701 | $result = array(); 702 | //print_r($matches); 703 | 704 | foreach ($matches as $m) { 705 | $m[0] = trim($m[0]); 706 | if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue; 707 | // for browser generated xpath 708 | if ($m[1]==='tbody') continue; 709 | 710 | list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false); 711 | if (!empty($m[2])) {$key='id'; $val=$m[2];} 712 | if (!empty($m[3])) {$key='class'; $val=$m[3];} 713 | if (!empty($m[4])) {$key=$m[4];} 714 | if (!empty($m[5])) {$exp=$m[5];} 715 | if (!empty($m[6])) {$val=$m[6];} 716 | 717 | // convert to lowercase 718 | if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);} 719 | //elements that do NOT have the specified attribute 720 | if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;} 721 | 722 | $result[] = array($tag, $key, $val, $exp, $no_key); 723 | if (trim($m[7])===',') { 724 | $selectors[] = $result; 725 | $result = array(); 726 | } 727 | } 728 | if (count($result)>0) 729 | $selectors[] = $result; 730 | return $selectors; 731 | } 732 | 733 | function __get($name) { 734 | if (isset($this->attr[$name])) 735 | { 736 | return $this->convert_text($this->attr[$name]); 737 | } 738 | switch ($name) { 739 | case 'outertext': return $this->outertext(); 740 | case 'innertext': return $this->innertext(); 741 | case 'plaintext': return $this->text(); 742 | case 'xmltext': return $this->xmltext(); 743 | default: return array_key_exists($name, $this->attr); 744 | } 745 | } 746 | 747 | function __set($name, $value) { 748 | switch ($name) { 749 | case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value; 750 | case 'innertext': 751 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value; 752 | return $this->_[HDOM_INFO_INNER] = $value; 753 | } 754 | if (!isset($this->attr[$name])) { 755 | $this->_[HDOM_INFO_SPACE][] = array(' ', '', ''); 756 | $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE; 757 | } 758 | $this->attr[$name] = $value; 759 | } 760 | 761 | function __isset($name) { 762 | switch ($name) { 763 | case 'outertext': return true; 764 | case 'innertext': return true; 765 | case 'plaintext': return true; 766 | } 767 | //no value attr: nowrap, checked selected... 768 | return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]); 769 | } 770 | 771 | function __unset($name) { 772 | if (isset($this->attr[$name])) 773 | unset($this->attr[$name]); 774 | } 775 | 776 | // PaperG - Function to convert the text from one character set to another if the two sets are not the same. 777 | function convert_text($text) 778 | { 779 | global $debugObject; 780 | if (is_object($debugObject)) {$debugObject->debugLogEntry(1);} 781 | 782 | $converted_text = $text; 783 | 784 | $sourceCharset = ""; 785 | $targetCharset = ""; 786 | 787 | if ($this->dom) 788 | { 789 | $sourceCharset = strtoupper($this->dom->_charset); 790 | $targetCharset = strtoupper($this->dom->_target_charset); 791 | } 792 | if (is_object($debugObject)) {$debugObject->debugLog(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);} 793 | 794 | if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0)) 795 | { 796 | // Check if the reported encoding could have been incorrect and the text is actually already UTF-8 797 | if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text))) 798 | { 799 | $converted_text = $text; 800 | } 801 | else 802 | { 803 | $converted_text = iconv($sourceCharset, $targetCharset, $text); 804 | } 805 | } 806 | 807 | // Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output. 808 | if ($targetCharset == 'UTF-8') 809 | { 810 | if (substr($converted_text, 0, 3) == "\xef\xbb\xbf") 811 | { 812 | $converted_text = substr($converted_text, 3); 813 | } 814 | if (substr($converted_text, -3) == "\xef\xbb\xbf") 815 | { 816 | $converted_text = substr($converted_text, 0, -3); 817 | } 818 | } 819 | 820 | return $converted_text; 821 | } 822 | 823 | /** 824 | * Returns true if $string is valid UTF-8 and false otherwise. 825 | * 826 | * @param mixed $str String to be tested 827 | * @return boolean 828 | */ 829 | static function is_utf8($str) 830 | { 831 | $c=0; $b=0; 832 | $bits=0; 833 | $len=strlen($str); 834 | for($i=0; $i<$len; $i++) 835 | { 836 | $c=ord($str[$i]); 837 | if($c > 128) 838 | { 839 | if(($c >= 254)) return false; 840 | elseif($c >= 252) $bits=6; 841 | elseif($c >= 248) $bits=5; 842 | elseif($c >= 240) $bits=4; 843 | elseif($c >= 224) $bits=3; 844 | elseif($c >= 192) $bits=2; 845 | else return false; 846 | if(($i+$bits) > $len) return false; 847 | while($bits > 1) 848 | { 849 | $i++; 850 | $b=ord($str[$i]); 851 | if($b < 128 || $b > 191) return false; 852 | $bits--; 853 | } 854 | } 855 | } 856 | return true; 857 | } 858 | /* 859 | function is_utf8($string) 860 | { 861 | //this is buggy 862 | return (utf8_encode(utf8_decode($string)) == $string); 863 | } 864 | */ 865 | 866 | /** 867 | * Function to try a few tricks to determine the displayed size of an img on the page. 868 | * NOTE: This will ONLY work on an IMG tag. Returns FALSE on all other tag types. 869 | * 870 | * @author John Schlick 871 | * @version April 19 2012 872 | * @return array an array containing the 'height' and 'width' of the image on the page or -1 if we can't figure it out. 873 | */ 874 | function get_display_size() 875 | { 876 | global $debugObject; 877 | 878 | $width = -1; 879 | $height = -1; 880 | 881 | if ($this->tag !== 'img') 882 | { 883 | return false; 884 | } 885 | 886 | // See if there is aheight or width attribute in the tag itself. 887 | if (isset($this->attr['width'])) 888 | { 889 | $width = $this->attr['width']; 890 | } 891 | 892 | if (isset($this->attr['height'])) 893 | { 894 | $height = $this->attr['height']; 895 | } 896 | 897 | // Now look for an inline style. 898 | if (isset($this->attr['style'])) 899 | { 900 | // Thanks to user gnarf from stackoverflow for this regular expression. 901 | $attributes = array(); 902 | preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $this->attr['style'], $matches, PREG_SET_ORDER); 903 | foreach ($matches as $match) { 904 | $attributes[$match[1]] = $match[2]; 905 | } 906 | 907 | // If there is a width in the style attributes: 908 | if (isset($attributes['width']) && $width == -1) 909 | { 910 | // check that the last two characters are px (pixels) 911 | if (strtolower(substr($attributes['width'], -2)) == 'px') 912 | { 913 | $proposed_width = substr($attributes['width'], 0, -2); 914 | // Now make sure that it's an integer and not something stupid. 915 | if (filter_var($proposed_width, FILTER_VALIDATE_INT)) 916 | { 917 | $width = $proposed_width; 918 | } 919 | } 920 | } 921 | 922 | // If there is a width in the style attributes: 923 | if (isset($attributes['height']) && $height == -1) 924 | { 925 | // check that the last two characters are px (pixels) 926 | if (strtolower(substr($attributes['height'], -2)) == 'px') 927 | { 928 | $proposed_height = substr($attributes['height'], 0, -2); 929 | // Now make sure that it's an integer and not something stupid. 930 | if (filter_var($proposed_height, FILTER_VALIDATE_INT)) 931 | { 932 | $height = $proposed_height; 933 | } 934 | } 935 | } 936 | 937 | } 938 | 939 | // Future enhancement: 940 | // Look in the tag to see if there is a class or id specified that has a height or width attribute to it. 941 | 942 | // Far future enhancement 943 | // Look at all the parent tags of this image to see if they specify a class or id that has an img selector that specifies a height or width 944 | // Note that in this case, the class or id will have the img subselector for it to apply to the image. 945 | 946 | // ridiculously far future development 947 | // If the class or id is specified in a SEPARATE css file thats not on the page, go get it and do what we were just doing for the ones on the page. 948 | 949 | $result = array('height' => $height, 950 | 'width' => $width); 951 | return $result; 952 | } 953 | 954 | // camel naming conventions 955 | function getAllAttributes() {return array_map('html_entity_decode', $this->attr);} 956 | function getAttribute($name) {return html_entity_decode($this->__get($name));} 957 | function setAttribute($name, $value) {$this->__set($name, $value);} 958 | function hasAttribute($name) {return $this->__isset($name);} 959 | function removeAttribute($name) {$this->__set($name, null);} 960 | function getElementById($id) {return $this->find("#$id", 0);} 961 | function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);} 962 | function getElementByTagName($name) {return $this->find($name, 0);} 963 | function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);} 964 | function parentNode() {return $this->parent();} 965 | function childNodes($idx=-1) {return $this->children($idx);} 966 | function firstChild() {return $this->first_child();} 967 | function lastChild() {return $this->last_child();} 968 | function nextSibling() {return $this->next_sibling();} 969 | function previousSibling() {return $this->prev_sibling();} 970 | function hasChildNodes() {return $this->has_child();} 971 | function nodeName() {return $this->tag;} 972 | function appendChild($node) {$node->parent($this); return $node;} 973 | 974 | } 975 | 976 | /** 977 | * simple html dom parser 978 | * Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector. 979 | * Paperg - change $size from protected to public so we can easily access it 980 | * Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it. 981 | * 982 | * @package PlaceLocalInclude 983 | */ 984 | class simple_html_dom 985 | { 986 | /** @var simple_html_dom_node $root */ 987 | public $root = null; 988 | public $nodes = array(); 989 | public $callback = null; 990 | public $lowercase = false; 991 | // Used to keep track of how large the text was when we started. 992 | public $original_size; 993 | public $size; 994 | protected $pos; 995 | protected $doc; 996 | protected $char; 997 | protected $cursor; 998 | protected $parent; 999 | protected $noise = array(); 1000 | protected $token_blank = " \t\r\n"; 1001 | protected $token_equal = ' =/>'; 1002 | protected $token_slash = " />\r\n\t"; 1003 | protected $token_attr = ' >'; 1004 | // Note that this is referenced by a child node, and so it needs to be public for that node to see this information. 1005 | public $_charset = ''; 1006 | public $_target_charset = ''; 1007 | protected $default_br_text = ""; 1008 | public $default_span_text = ""; 1009 | 1010 | // use isset instead of in_array, performance boost about 30%... 1011 | protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1); 1012 | protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1); 1013 | // Known sourceforge issue #2977341 1014 | // B tags that are not closed cause us to return everything to the end of the document. 1015 | protected $optional_closing_tags = array( 1016 | 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1), 1017 | 'th'=>array('th'=>1), 1018 | 'td'=>array('td'=>1), 1019 | 'li'=>array('li'=>1), 1020 | 'dt'=>array('dt'=>1, 'dd'=>1), 1021 | 'dd'=>array('dd'=>1, 'dt'=>1), 1022 | 'dl'=>array('dd'=>1, 'dt'=>1), 1023 | 'p'=>array('p'=>1), 1024 | 'nobr'=>array('nobr'=>1), 1025 | 'b'=>array('b'=>1), 1026 | 'option'=>array('option'=>1), 1027 | ); 1028 | 1029 | function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 1030 | { 1031 | if ($str) 1032 | { 1033 | if (preg_match("/^http:\/\//i",$str) || is_file($str)) 1034 | { 1035 | $this->load_file($str); 1036 | } 1037 | else 1038 | { 1039 | $this->load($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText); 1040 | } 1041 | } 1042 | // Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html. 1043 | if (!$forceTagsClosed) { 1044 | $this->optional_closing_array=array(); 1045 | } 1046 | $this->_target_charset = $target_charset; 1047 | } 1048 | 1049 | function __destruct() 1050 | { 1051 | $this->clear(); 1052 | } 1053 | 1054 | // load html from string 1055 | function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 1056 | { 1057 | global $debugObject; 1058 | 1059 | // prepare 1060 | $this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText); 1061 | // strip out comments 1062 | $this->remove_noise("''is"); 1063 | // strip out cdata 1064 | $this->remove_noise("''is", true); 1065 | // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037 1066 | // Script tags removal now preceeds style tag removal. 1067 | // strip out