PageRenderTime 67ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/application/vendor/simplehtmldom/simple_html_dom.php

https://bitbucket.org/rlm3/mrs
PHP | 975 lines | 844 code | 68 blank | 63 comment | 86 complexity | df74d63d1e51e910e1fb719b241d6e46 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /*******************************************************************************
  3. Version: 1.11 ($Rev: 175 $)
  4. Website: http://sourceforge.net/projects/simplehtmldom/
  5. Author: S.C. Chen <me578022@gmail.com>
  6. Acknowledge: Jose Solorzano (https://sourceforge.net/projects/php-html/)
  7. Contributions by:
  8. Yousuke Kumakura (Attribute filters)
  9. Vadim Voituk (Negative indexes supports of "find" method)
  10. Antcs (Constructor with automatically load contents either text or file/url)
  11. Licensed under The MIT License
  12. Redistributions of files must retain the above copyright notice.
  13. *******************************************************************************/
  14. define('HDOM_TYPE_ELEMENT', 1);
  15. define('HDOM_TYPE_COMMENT', 2);
  16. define('HDOM_TYPE_TEXT', 3);
  17. define('HDOM_TYPE_ENDTAG', 4);
  18. define('HDOM_TYPE_ROOT', 5);
  19. define('HDOM_TYPE_UNKNOWN', 6);
  20. define('HDOM_QUOTE_DOUBLE', 0);
  21. define('HDOM_QUOTE_SINGLE', 1);
  22. define('HDOM_QUOTE_NO', 3);
  23. define('HDOM_INFO_BEGIN', 0);
  24. define('HDOM_INFO_END', 1);
  25. define('HDOM_INFO_QUOTE', 2);
  26. define('HDOM_INFO_SPACE', 3);
  27. define('HDOM_INFO_TEXT', 4);
  28. define('HDOM_INFO_INNER', 5);
  29. define('HDOM_INFO_OUTER', 6);
  30. define('HDOM_INFO_ENDSPACE',7);
  31. // helper functions
  32. // -----------------------------------------------------------------------------
  33. // get html dom form file
  34. function file_get_html() {
  35. $dom = new simple_html_dom;
  36. $args = func_get_args();
  37. $dom->load(call_user_func_array('file_get_contents', $args), true);
  38. return $dom;
  39. }
  40. // get html dom form string
  41. function str_get_html($str, $lowercase=true) {
  42. $dom = new simple_html_dom;
  43. $dom->load($str, $lowercase);
  44. return $dom;
  45. }
  46. // dump html dom tree
  47. function dump_html_tree($node, $show_attr=true, $deep=0) {
  48. $lead = str_repeat(' ', $deep);
  49. echo $lead.$node->tag;
  50. if ($show_attr && count($node->attr)>0) {
  51. echo '(';
  52. foreach($node->attr as $k=>$v)
  53. echo "[$k]=>\"".$node->$k.'", ';
  54. echo ')';
  55. }
  56. echo "\n";
  57. foreach($node->nodes as $c)
  58. dump_html_tree($c, $show_attr, $deep+1);
  59. }
  60. // get dom form file (deprecated)
  61. function file_get_dom() {
  62. $dom = new simple_html_dom;
  63. $args = func_get_args();
  64. $dom->load(call_user_func_array('file_get_contents', $args), true);
  65. return $dom;
  66. }
  67. // get dom form string (deprecated)
  68. function str_get_dom($str, $lowercase=true) {
  69. $dom = new simple_html_dom;
  70. $dom->load($str, $lowercase);
  71. return $dom;
  72. }
  73. // simple html dom node
  74. // -----------------------------------------------------------------------------
  75. class simple_html_dom_node {
  76. public $nodetype = HDOM_TYPE_TEXT;
  77. public $tag = 'text';
  78. public $attr = array();
  79. public $children = array();
  80. public $nodes = array();
  81. public $parent = null;
  82. public $_ = array();
  83. private $dom = null;
  84. function __construct($dom) {
  85. $this->dom = $dom;
  86. $dom->nodes[] = $this;
  87. }
  88. function __destruct() {
  89. $this->clear();
  90. }
  91. function __toString() {
  92. return $this->outertext();
  93. }
  94. // clean up memory due to php5 circular references memory leak...
  95. function clear() {
  96. $this->dom = null;
  97. $this->nodes = null;
  98. $this->parent = null;
  99. $this->children = null;
  100. }
  101. // dump node's tree
  102. function dump($show_attr=true) {
  103. dump_html_tree($this, $show_attr);
  104. }
  105. // returns the parent of node
  106. function parent() {
  107. return $this->parent;
  108. }
  109. // returns children of node
  110. function children($idx=-1) {
  111. if ($idx===-1) return $this->children;
  112. if (isset($this->children[$idx])) return $this->children[$idx];
  113. return null;
  114. }
  115. // returns the first child of node
  116. function first_child() {
  117. if (count($this->children)>0) return $this->children[0];
  118. return null;
  119. }
  120. // returns the last child of node
  121. function last_child() {
  122. if (($count=count($this->children))>0) return $this->children[$count-1];
  123. return null;
  124. }
  125. // returns the next sibling of node
  126. function next_sibling() {
  127. if ($this->parent===null) return null;
  128. $idx = 0;
  129. $count = count($this->parent->children);
  130. while ($idx<$count && $this!==$this->parent->children[$idx])
  131. ++$idx;
  132. if (++$idx>=$count) return null;
  133. return $this->parent->children[$idx];
  134. }
  135. // returns the previous sibling of node
  136. function prev_sibling() {
  137. if ($this->parent===null) return null;
  138. $idx = 0;
  139. $count = count($this->parent->children);
  140. while ($idx<$count && $this!==$this->parent->children[$idx])
  141. ++$idx;
  142. if (--$idx<0) return null;
  143. return $this->parent->children[$idx];
  144. }
  145. // get dom node's inner html
  146. function innertext() {
  147. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  148. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  149. $ret = '';
  150. foreach($this->nodes as $n)
  151. $ret .= $n->outertext();
  152. return $ret;
  153. }
  154. // get dom node's outer text (with tag)
  155. function outertext() {
  156. if ($this->tag==='root') return $this->innertext();
  157. // trigger callback
  158. if ($this->dom->callback!==null)
  159. call_user_func_array($this->dom->callback, array($this));
  160. if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER];
  161. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  162. // render begin tag
  163. $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup();
  164. // render inner text
  165. if (isset($this->_[HDOM_INFO_INNER]))
  166. $ret .= $this->_[HDOM_INFO_INNER];
  167. else {
  168. foreach($this->nodes as $n)
  169. $ret .= $n->outertext();
  170. }
  171. // render end tag
  172. if(isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0)
  173. $ret .= '</'.$this->tag.'>';
  174. return $ret;
  175. }
  176. // get dom node's plain text
  177. function text() {
  178. if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER];
  179. switch ($this->nodetype) {
  180. case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  181. case HDOM_TYPE_COMMENT: return '';
  182. case HDOM_TYPE_UNKNOWN: return '';
  183. }
  184. if (strcasecmp($this->tag, 'script')===0) return '';
  185. if (strcasecmp($this->tag, 'style')===0) return '';
  186. $ret = '';
  187. foreach($this->nodes as $n)
  188. $ret .= $n->text();
  189. return $ret;
  190. }
  191. function xmltext() {
  192. $ret = $this->innertext();
  193. $ret = str_ireplace('<![CDATA[', '', $ret);
  194. $ret = str_replace(']]>', '', $ret);
  195. return $ret;
  196. }
  197. // build node's text with tag
  198. function makeup() {
  199. // text, comment, unknown
  200. if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]);
  201. $ret = '<'.$this->tag;
  202. $i = -1;
  203. foreach($this->attr as $key=>$val) {
  204. ++$i;
  205. // skip removed attribute
  206. if ($val===null || $val===false)
  207. continue;
  208. $ret .= $this->_[HDOM_INFO_SPACE][$i][0];
  209. //no value attr: nowrap, checked selected...
  210. if ($val===true)
  211. $ret .= $key;
  212. else {
  213. switch($this->_[HDOM_INFO_QUOTE][$i]) {
  214. case HDOM_QUOTE_DOUBLE: $quote = '"'; break;
  215. case HDOM_QUOTE_SINGLE: $quote = '\''; break;
  216. default: $quote = '';
  217. }
  218. $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote;
  219. }
  220. }
  221. $ret = $this->dom->restore_noise($ret);
  222. return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>';
  223. }
  224. // find elements by css selector
  225. function find($selector, $idx=null) {
  226. $selectors = $this->parse_selector($selector);
  227. if (($count=count($selectors))===0) return array();
  228. $found_keys = array();
  229. // find each selector
  230. for ($c=0; $c<$count; ++$c) {
  231. if (($levle=count($selectors[0]))===0) return array();
  232. if (!isset($this->_[HDOM_INFO_BEGIN])) return array();
  233. $head = array($this->_[HDOM_INFO_BEGIN]=>1);
  234. // handle descendant selectors, no recursive!
  235. for ($l=0; $l<$levle; ++$l) {
  236. $ret = array();
  237. foreach($head as $k=>$v) {
  238. $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k];
  239. $n->seek($selectors[$c][$l], $ret);
  240. }
  241. $head = $ret;
  242. }
  243. foreach($head as $k=>$v) {
  244. if (!isset($found_keys[$k]))
  245. $found_keys[$k] = 1;
  246. }
  247. }
  248. // sort keys
  249. ksort($found_keys);
  250. $found = array();
  251. foreach($found_keys as $k=>$v)
  252. $found[] = $this->dom->nodes[$k];
  253. // return nth-element or array
  254. if (is_null($idx)) return $found;
  255. else if ($idx<0) $idx = count($found) + $idx;
  256. return (isset($found[$idx])) ? $found[$idx] : null;
  257. }
  258. // seek for given conditions
  259. protected function seek($selector, &$ret) {
  260. list($tag, $key, $val, $exp, $no_key) = $selector;
  261. // xpath index
  262. if ($tag && $key && is_numeric($key)) {
  263. $count = 0;
  264. foreach ($this->children as $c) {
  265. if ($tag==='*' || $tag===$c->tag) {
  266. if (++$count==$key) {
  267. $ret[$c->_[HDOM_INFO_BEGIN]] = 1;
  268. return;
  269. }
  270. }
  271. }
  272. return;
  273. }
  274. $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0;
  275. if ($end==0) {
  276. $parent = $this->parent;
  277. while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) {
  278. $end -= 1;
  279. $parent = $parent->parent;
  280. }
  281. $end += $parent->_[HDOM_INFO_END];
  282. }
  283. for($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) {
  284. $node = $this->dom->nodes[$i];
  285. $pass = true;
  286. if ($tag==='*' && !$key) {
  287. if (in_array($node, $this->children, true))
  288. $ret[$i] = 1;
  289. continue;
  290. }
  291. // compare tag
  292. if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;}
  293. // compare key
  294. if ($pass && $key) {
  295. if ($no_key) {
  296. if (isset($node->attr[$key])) $pass=false;
  297. }
  298. else if (!isset($node->attr[$key])) $pass=false;
  299. }
  300. // compare value
  301. if ($pass && $key && $val && $val!=='*') {
  302. $check = $this->match($exp, $val, $node->attr[$key]);
  303. // handle multiple class
  304. if (!$check && strcasecmp($key, 'class')===0) {
  305. foreach(explode(' ',$node->attr[$key]) as $k) {
  306. $check = $this->match($exp, $val, $k);
  307. if ($check) break;
  308. }
  309. }
  310. if (!$check) $pass = false;
  311. }
  312. if ($pass) $ret[$i] = 1;
  313. unset($node);
  314. }
  315. }
  316. protected function match($exp, $pattern, $value) {
  317. switch ($exp) {
  318. case '=':
  319. return ($value===$pattern);
  320. case '!=':
  321. return ($value!==$pattern);
  322. case '^=':
  323. return preg_match("/^".preg_quote($pattern,'/')."/", $value);
  324. case '$=':
  325. return preg_match("/".preg_quote($pattern,'/')."$/", $value);
  326. case '*=':
  327. if ($pattern[0]=='/')
  328. return preg_match($pattern, $value);
  329. return preg_match("/".$pattern."/i", $value);
  330. }
  331. return false;
  332. }
  333. protected function parse_selector($selector_string) {
  334. // pattern of CSS selectors, modified from mootools
  335. $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is";
  336. preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER);
  337. $selectors = array();
  338. $result = array();
  339. //print_r($matches);
  340. foreach ($matches as $m) {
  341. $m[0] = trim($m[0]);
  342. if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue;
  343. // for borwser grnreated xpath
  344. if ($m[1]==='tbody') continue;
  345. list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false);
  346. if(!empty($m[2])) {$key='id'; $val=$m[2];}
  347. if(!empty($m[3])) {$key='class'; $val=$m[3];}
  348. if(!empty($m[4])) {$key=$m[4];}
  349. if(!empty($m[5])) {$exp=$m[5];}
  350. if(!empty($m[6])) {$val=$m[6];}
  351. // convert to lowercase
  352. if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);}
  353. //elements that do NOT have the specified attribute
  354. if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;}
  355. $result[] = array($tag, $key, $val, $exp, $no_key);
  356. if (trim($m[7])===',') {
  357. $selectors[] = $result;
  358. $result = array();
  359. }
  360. }
  361. if (count($result)>0)
  362. $selectors[] = $result;
  363. return $selectors;
  364. }
  365. function __get($name) {
  366. if (isset($this->attr[$name])) return $this->attr[$name];
  367. switch($name) {
  368. case 'outertext': return $this->outertext();
  369. case 'innertext': return $this->innertext();
  370. case 'plaintext': return $this->text();
  371. case 'xmltext': return $this->xmltext();
  372. default: return array_key_exists($name, $this->attr);
  373. }
  374. }
  375. function __set($name, $value) {
  376. switch($name) {
  377. case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value;
  378. case 'innertext':
  379. if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value;
  380. return $this->_[HDOM_INFO_INNER] = $value;
  381. }
  382. if (!isset($this->attr[$name])) {
  383. $this->_[HDOM_INFO_SPACE][] = array(' ', '', '');
  384. $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  385. }
  386. $this->attr[$name] = $value;
  387. }
  388. function __isset($name) {
  389. switch($name) {
  390. case 'outertext': return true;
  391. case 'innertext': return true;
  392. case 'plaintext': return true;
  393. }
  394. //no value attr: nowrap, checked selected...
  395. return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]);
  396. }
  397. function __unset($name) {
  398. if (isset($this->attr[$name]))
  399. unset($this->attr[$name]);
  400. }
  401. // camel naming conventions
  402. function getAllAttributes() {return $this->attr;}
  403. function getAttribute($name) {return $this->__get($name);}
  404. function setAttribute($name, $value) {$this->__set($name, $value);}
  405. function hasAttribute($name) {return $this->__isset($name);}
  406. function removeAttribute($name) {$this->__set($name, null);}
  407. function getElementById($id) {return $this->find("#$id", 0);}
  408. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  409. function getElementByTagName($name) {return $this->find($name, 0);}
  410. function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);}
  411. function parentNode() {return $this->parent();}
  412. function childNodes($idx=-1) {return $this->children($idx);}
  413. function firstChild() {return $this->first_child();}
  414. function lastChild() {return $this->last_child();}
  415. function nextSibling() {return $this->next_sibling();}
  416. function previousSibling() {return $this->prev_sibling();}
  417. }
  418. // simple html dom parser
  419. // -----------------------------------------------------------------------------
  420. class simple_html_dom {
  421. public $root = null;
  422. public $nodes = array();
  423. public $callback = null;
  424. public $lowercase = false;
  425. protected $pos;
  426. protected $doc;
  427. protected $char;
  428. protected $size;
  429. protected $cursor;
  430. protected $parent;
  431. protected $noise = array();
  432. protected $token_blank = " \t\r\n";
  433. protected $token_equal = ' =/>';
  434. protected $token_slash = " />\r\n\t";
  435. protected $token_attr = ' >';
  436. // use isset instead of in_array, performance boost about 30%...
  437. protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1);
  438. protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1);
  439. protected $optional_closing_tags = array(
  440. 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1),
  441. 'th'=>array('th'=>1),
  442. 'td'=>array('td'=>1),
  443. 'li'=>array('li'=>1),
  444. 'dt'=>array('dt'=>1, 'dd'=>1),
  445. 'dd'=>array('dd'=>1, 'dt'=>1),
  446. 'dl'=>array('dd'=>1, 'dt'=>1),
  447. 'p'=>array('p'=>1),
  448. 'nobr'=>array('nobr'=>1),
  449. );
  450. function __construct($str=null) {
  451. if ($str) {
  452. if (preg_match("/^http:\/\//i",$str) || is_file($str))
  453. $this->load_file($str);
  454. else
  455. $this->load($str);
  456. }
  457. }
  458. function __destruct() {
  459. $this->clear();
  460. }
  461. // load html from string
  462. function load($str, $lowercase=true) {
  463. // prepare
  464. $this->prepare($str, $lowercase);
  465. // strip out comments
  466. $this->remove_noise("'<!--(.*?)-->'is");
  467. // strip out cdata
  468. $this->remove_noise("'<!\[CDATA\[(.*?)\]\]>'is", true);
  469. // strip out <style> tags
  470. $this->remove_noise("'<\s*style[^>]*[^/]>(.*?)<\s*/\s*style\s*>'is");
  471. $this->remove_noise("'<\s*style\s*>(.*?)<\s*/\s*style\s*>'is");
  472. // strip out <script> tags
  473. $this->remove_noise("'<\s*script[^>]*[^/]>(.*?)<\s*/\s*script\s*>'is");
  474. $this->remove_noise("'<\s*script\s*>(.*?)<\s*/\s*script\s*>'is");
  475. // strip out preformatted tags
  476. $this->remove_noise("'<\s*(?:code)[^>]*>(.*?)<\s*/\s*(?:code)\s*>'is");
  477. // strip out server side scripts
  478. $this->remove_noise("'(<\?)(.*?)(\?>)'s", true);
  479. // strip smarty scripts
  480. $this->remove_noise("'(\{\w)(.*?)(\})'s", true);
  481. // parsing
  482. while ($this->parse());
  483. // end
  484. $this->root->_[HDOM_INFO_END] = $this->cursor;
  485. }
  486. // load html from file
  487. function load_file() {
  488. $args = func_get_args();
  489. $this->load(call_user_func_array('file_get_contents', $args), true);
  490. }
  491. // set callback function
  492. function set_callback($function_name) {
  493. $this->callback = $function_name;
  494. }
  495. // remove callback function
  496. function remove_callback() {
  497. $this->callback = null;
  498. }
  499. // save dom as string
  500. function save($filepath='') {
  501. $ret = $this->root->innertext();
  502. if ($filepath!=='') file_put_contents($filepath, $ret);
  503. return $ret;
  504. }
  505. // find dom node by css selector
  506. function find($selector, $idx=null) {
  507. return $this->root->find($selector, $idx);
  508. }
  509. // clean up memory due to php5 circular references memory leak...
  510. function clear() {
  511. foreach($this->nodes as $n) {$n->clear(); $n = null;}
  512. if (isset($this->parent)) {$this->parent->clear(); unset($this->parent);}
  513. if (isset($this->root)) {$this->root->clear(); unset($this->root);}
  514. unset($this->doc);
  515. unset($this->noise);
  516. }
  517. function dump($show_attr=true) {
  518. $this->root->dump($show_attr);
  519. }
  520. // prepare HTML data and init everything
  521. protected function prepare($str, $lowercase=true) {
  522. $this->clear();
  523. $this->doc = $str;
  524. $this->pos = 0;
  525. $this->cursor = 1;
  526. $this->noise = array();
  527. $this->nodes = array();
  528. $this->lowercase = $lowercase;
  529. $this->root = new simple_html_dom_node($this);
  530. $this->root->tag = 'root';
  531. $this->root->_[HDOM_INFO_BEGIN] = -1;
  532. $this->root->nodetype = HDOM_TYPE_ROOT;
  533. $this->parent = $this->root;
  534. // set the length of content
  535. $this->size = strlen($str);
  536. if ($this->size>0) $this->char = $this->doc[0];
  537. }
  538. // parse html content
  539. protected function parse() {
  540. if (($s = $this->copy_until_char('<'))==='')
  541. return $this->read_tag();
  542. // text
  543. $node = new simple_html_dom_node($this);
  544. ++$this->cursor;
  545. $node->_[HDOM_INFO_TEXT] = $s;
  546. $this->link_nodes($node, false);
  547. return true;
  548. }
  549. // read tag info
  550. protected function read_tag() {
  551. if ($this->char!=='<') {
  552. $this->root->_[HDOM_INFO_END] = $this->cursor;
  553. return false;
  554. }
  555. $begin_tag_pos = $this->pos;
  556. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  557. // end tag
  558. if ($this->char==='/') {
  559. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  560. $this->skip($this->token_blank_t);
  561. $tag = $this->copy_until_char('>');
  562. // skip attributes in end tag
  563. if (($pos = strpos($tag, ' '))!==false)
  564. $tag = substr($tag, 0, $pos);
  565. $parent_lower = strtolower($this->parent->tag);
  566. $tag_lower = strtolower($tag);
  567. if ($parent_lower!==$tag_lower) {
  568. if (isset($this->optional_closing_tags[$parent_lower]) && isset($this->block_tags[$tag_lower])) {
  569. $this->parent->_[HDOM_INFO_END] = 0;
  570. $org_parent = $this->parent;
  571. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  572. $this->parent = $this->parent->parent;
  573. if (strtolower($this->parent->tag)!==$tag_lower) {
  574. $this->parent = $org_parent; // restore origonal parent
  575. if ($this->parent->parent) $this->parent = $this->parent->parent;
  576. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  577. return $this->as_text_node($tag);
  578. }
  579. }
  580. else if (($this->parent->parent) && isset($this->block_tags[$tag_lower])) {
  581. $this->parent->_[HDOM_INFO_END] = 0;
  582. $org_parent = $this->parent;
  583. while (($this->parent->parent) && strtolower($this->parent->tag)!==$tag_lower)
  584. $this->parent = $this->parent->parent;
  585. if (strtolower($this->parent->tag)!==$tag_lower) {
  586. $this->parent = $org_parent; // restore origonal parent
  587. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  588. return $this->as_text_node($tag);
  589. }
  590. }
  591. else if (($this->parent->parent) && strtolower($this->parent->parent->tag)===$tag_lower) {
  592. $this->parent->_[HDOM_INFO_END] = 0;
  593. $this->parent = $this->parent->parent;
  594. }
  595. else
  596. return $this->as_text_node($tag);
  597. }
  598. $this->parent->_[HDOM_INFO_END] = $this->cursor;
  599. if ($this->parent->parent) $this->parent = $this->parent->parent;
  600. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  601. return true;
  602. }
  603. $node = new simple_html_dom_node($this);
  604. $node->_[HDOM_INFO_BEGIN] = $this->cursor;
  605. ++$this->cursor;
  606. $tag = $this->copy_until($this->token_slash);
  607. // doctype, cdata & comments...
  608. if (isset($tag[0]) && $tag[0]==='!') {
  609. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until_char('>');
  610. if (isset($tag[2]) && $tag[1]==='-' && $tag[2]==='-') {
  611. $node->nodetype = HDOM_TYPE_COMMENT;
  612. $node->tag = 'comment';
  613. } else {
  614. $node->nodetype = HDOM_TYPE_UNKNOWN;
  615. $node->tag = 'unknown';
  616. }
  617. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  618. $this->link_nodes($node, true);
  619. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  620. return true;
  621. }
  622. // text
  623. if ($pos=strpos($tag, '<')!==false) {
  624. $tag = '<' . substr($tag, 0, -1);
  625. $node->_[HDOM_INFO_TEXT] = $tag;
  626. $this->link_nodes($node, false);
  627. $this->char = $this->doc[--$this->pos]; // prev
  628. return true;
  629. }
  630. if (!preg_match("/^[\w-:]+$/", $tag)) {
  631. $node->_[HDOM_INFO_TEXT] = '<' . $tag . $this->copy_until('<>');
  632. if ($this->char==='<') {
  633. $this->link_nodes($node, false);
  634. return true;
  635. }
  636. if ($this->char==='>') $node->_[HDOM_INFO_TEXT].='>';
  637. $this->link_nodes($node, false);
  638. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  639. return true;
  640. }
  641. // begin tag
  642. $node->nodetype = HDOM_TYPE_ELEMENT;
  643. $tag_lower = strtolower($tag);
  644. $node->tag = ($this->lowercase) ? $tag_lower : $tag;
  645. // handle optional closing tags
  646. if (isset($this->optional_closing_tags[$tag_lower]) ) {
  647. while (isset($this->optional_closing_tags[$tag_lower][strtolower($this->parent->tag)])) {
  648. $this->parent->_[HDOM_INFO_END] = 0;
  649. $this->parent = $this->parent->parent;
  650. }
  651. $node->parent = $this->parent;
  652. }
  653. $guard = 0; // prevent infinity loop
  654. $space = array($this->copy_skip($this->token_blank), '', '');
  655. // attributes
  656. do {
  657. if ($this->char!==null && $space[0]==='') break;
  658. $name = $this->copy_until($this->token_equal);
  659. if($guard===$this->pos) {
  660. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  661. continue;
  662. }
  663. $guard = $this->pos;
  664. // handle endless '<'
  665. if($this->pos>=$this->size-1 && $this->char!=='>') {
  666. $node->nodetype = HDOM_TYPE_TEXT;
  667. $node->_[HDOM_INFO_END] = 0;
  668. $node->_[HDOM_INFO_TEXT] = '<'.$tag . $space[0] . $name;
  669. $node->tag = 'text';
  670. $this->link_nodes($node, false);
  671. return true;
  672. }
  673. // handle mismatch '<'
  674. if($this->doc[$this->pos-1]=='<') {
  675. $node->nodetype = HDOM_TYPE_TEXT;
  676. $node->tag = 'text';
  677. $node->attr = array();
  678. $node->_[HDOM_INFO_END] = 0;
  679. $node->_[HDOM_INFO_TEXT] = substr($this->doc, $begin_tag_pos, $this->pos-$begin_tag_pos-1);
  680. $this->pos -= 2;
  681. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  682. $this->link_nodes($node, false);
  683. return true;
  684. }
  685. if ($name!=='/' && $name!=='') {
  686. $space[1] = $this->copy_skip($this->token_blank);
  687. $name = $this->restore_noise($name);
  688. if ($this->lowercase) $name = strtolower($name);
  689. if ($this->char==='=') {
  690. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  691. $this->parse_attr($node, $name, $space);
  692. }
  693. else {
  694. //no value attr: nowrap, checked selected...
  695. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  696. $node->attr[$name] = true;
  697. if ($this->char!='>') $this->char = $this->doc[--$this->pos]; // prev
  698. }
  699. $node->_[HDOM_INFO_SPACE][] = $space;
  700. $space = array($this->copy_skip($this->token_blank), '', '');
  701. }
  702. else
  703. break;
  704. } while($this->char!=='>' && $this->char!=='/');
  705. $this->link_nodes($node, true);
  706. $node->_[HDOM_INFO_ENDSPACE] = $space[0];
  707. // check self closing
  708. if ($this->copy_until_char_escape('>')==='/') {
  709. $node->_[HDOM_INFO_ENDSPACE] .= '/';
  710. $node->_[HDOM_INFO_END] = 0;
  711. }
  712. else {
  713. // reset parent
  714. if (!isset($this->self_closing_tags[strtolower($node->tag)])) $this->parent = $node;
  715. }
  716. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  717. return true;
  718. }
  719. // parse attributes
  720. protected function parse_attr($node, $name, &$space) {
  721. $space[2] = $this->copy_skip($this->token_blank);
  722. switch($this->char) {
  723. case '"':
  724. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE;
  725. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  726. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('"'));
  727. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  728. break;
  729. case '\'':
  730. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_SINGLE;
  731. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  732. $node->attr[$name] = $this->restore_noise($this->copy_until_char_escape('\''));
  733. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  734. break;
  735. default:
  736. $node->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_NO;
  737. $node->attr[$name] = $this->restore_noise($this->copy_until($this->token_attr));
  738. }
  739. }
  740. // link node's parent
  741. protected function link_nodes(&$node, $is_child) {
  742. $node->parent = $this->parent;
  743. $this->parent->nodes[] = $node;
  744. if ($is_child)
  745. $this->parent->children[] = $node;
  746. }
  747. // as a text node
  748. protected function as_text_node($tag) {
  749. $node = new simple_html_dom_node($this);
  750. ++$this->cursor;
  751. $node->_[HDOM_INFO_TEXT] = '</' . $tag . '>';
  752. $this->link_nodes($node, false);
  753. $this->char = (++$this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  754. return true;
  755. }
  756. protected function skip($chars) {
  757. $this->pos += strspn($this->doc, $chars, $this->pos);
  758. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  759. }
  760. protected function copy_skip($chars) {
  761. $pos = $this->pos;
  762. $len = strspn($this->doc, $chars, $pos);
  763. $this->pos += $len;
  764. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  765. if ($len===0) return '';
  766. return substr($this->doc, $pos, $len);
  767. }
  768. protected function copy_until($chars) {
  769. $pos = $this->pos;
  770. $len = strcspn($this->doc, $chars, $pos);
  771. $this->pos += $len;
  772. $this->char = ($this->pos<$this->size) ? $this->doc[$this->pos] : null; // next
  773. return substr($this->doc, $pos, $len);
  774. }
  775. protected function copy_until_char($char) {
  776. if ($this->char===null) return '';
  777. if (($pos = strpos($this->doc, $char, $this->pos))===false) {
  778. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  779. $this->char = null;
  780. $this->pos = $this->size;
  781. return $ret;
  782. }
  783. if ($pos===$this->pos) return '';
  784. $pos_old = $this->pos;
  785. $this->char = $this->doc[$pos];
  786. $this->pos = $pos;
  787. return substr($this->doc, $pos_old, $pos-$pos_old);
  788. }
  789. protected function copy_until_char_escape($char) {
  790. if ($this->char===null) return '';
  791. $start = $this->pos;
  792. while(1) {
  793. if (($pos = strpos($this->doc, $char, $start))===false) {
  794. $ret = substr($this->doc, $this->pos, $this->size-$this->pos);
  795. $this->char = null;
  796. $this->pos = $this->size;
  797. return $ret;
  798. }
  799. if ($pos===$this->pos) return '';
  800. if ($this->doc[$pos-1]==='\\') {
  801. $start = $pos+1;
  802. continue;
  803. }
  804. $pos_old = $this->pos;
  805. $this->char = $this->doc[$pos];
  806. $this->pos = $pos;
  807. return substr($this->doc, $pos_old, $pos-$pos_old);
  808. }
  809. }
  810. // remove noise from html content
  811. protected function remove_noise($pattern, $remove_tag=false) {
  812. $count = preg_match_all($pattern, $this->doc, $matches, PREG_SET_ORDER|PREG_OFFSET_CAPTURE);
  813. for ($i=$count-1; $i>-1; --$i) {
  814. $key = '___noise___'.sprintf('% 3d', count($this->noise)+100);
  815. $idx = ($remove_tag) ? 0 : 1;
  816. $this->noise[$key] = $matches[$i][$idx][0];
  817. $this->doc = substr_replace($this->doc, $key, $matches[$i][$idx][1], strlen($matches[$i][$idx][0]));
  818. }
  819. // reset the length of content
  820. $this->size = strlen($this->doc);
  821. if ($this->size>0) $this->char = $this->doc[0];
  822. }
  823. // restore noise to html content
  824. function restore_noise($text) {
  825. while(($pos=strpos($text, '___noise___'))!==false) {
  826. $key = '___noise___'.$text[$pos+11].$text[$pos+12].$text[$pos+13];
  827. if (isset($this->noise[$key]))
  828. $text = substr($text, 0, $pos).$this->noise[$key].substr($text, $pos+14);
  829. }
  830. return $text;
  831. }
  832. function __toString() {
  833. return $this->root->innertext();
  834. }
  835. function __get($name) {
  836. switch($name) {
  837. case 'outertext': return $this->root->innertext();
  838. case 'innertext': return $this->root->innertext();
  839. case 'plaintext': return $this->root->text();
  840. }
  841. }
  842. // camel naming conventions
  843. function childNodes($idx=-1) {return $this->root->childNodes($idx);}
  844. function firstChild() {return $this->root->first_child();}
  845. function lastChild() {return $this->root->last_child();}
  846. function getElementById($id) {return $this->find("#$id", 0);}
  847. function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);}
  848. function getElementByTagName($name) {return $this->find($name, 0);}
  849. function getElementsByTagName($name, $idx=-1) {return $this->find($name, $idx);}
  850. function loadFile() {$args = func_get_args();$this->load(call_user_func_array('file_get_contents', $args), true);}
  851. }
  852. ?>