You are here

function simple_html_dom_node::find in simplehtmldom API 7

Same name and namespace in other branches
  1. 5.2 simplehtmldom/simple_html_dom.php \simple_html_dom_node::find()
  2. 6 simplehtmldom/simple_html_dom.php \simple_html_dom_node::find()
4 calls to simple_html_dom_node::find()
simple_html_dom_node::getElementById in simplehtmldom/simple_html_dom.php
simple_html_dom_node::getElementByTagName in simplehtmldom/simple_html_dom.php
simple_html_dom_node::getElementsById in simplehtmldom/simple_html_dom.php
simple_html_dom_node::getElementsByTagName in simplehtmldom/simple_html_dom.php

File

simplehtmldom/simple_html_dom.php, line 261

Class

simple_html_dom_node

Code

function find($selector, $idx = null) {
  $selectors = $this
    ->parse_selector($selector);
  if (($count = count($selectors)) === 0) {
    return array();
  }
  $found_keys = array();

  // find each selector
  for ($c = 0; $c < $count; ++$c) {
    if (($levle = count($selectors[0])) === 0) {
      return array();
    }
    if (!isset($this->_[HDOM_INFO_BEGIN])) {
      return array();
    }
    $head = array(
      $this->_[HDOM_INFO_BEGIN] => 1,
    );

    // handle descendant selectors, no recursive!
    for ($l = 0; $l < $levle; ++$l) {
      $ret = array();
      foreach ($head as $k => $v) {
        $n = $k === -1 ? $this->dom->root : $this->dom->nodes[$k];
        $n
          ->seek($selectors[$c][$l], $ret);
      }
      $head = $ret;
    }
    foreach ($head as $k => $v) {
      if (!isset($found_keys[$k])) {
        $found_keys[$k] = 1;
      }
    }
  }

  // sort keys
  ksort($found_keys);
  $found = array();
  foreach ($found_keys as $k => $v) {
    $found[] = $this->dom->nodes[$k];
  }

  // return nth-element or array
  if (is_null($idx)) {
    return $found;
  }
  else {
    if ($idx < 0) {
      $idx = count($found) + $idx;
    }
  }
  return isset($found[$idx]) ? $found[$idx] : null;
}