Skip to content Skip to sidebar Skip to footer

Extract Cell Value From Table Based On Another Cells Value

HTML file: http://www.arifoorum.com/test/html.htm I got this html contents with simplehtmldom library: array(66) { [0]=> array(14) { [0]=> string(4) 'Item'

Solution 1:

This could be useful for other users, so I made a little function that gets the value of a cell from a table, based on values of other cells (conditions):

functiongetCellValue(DOMElement $table, $cellName = null, array$conditions = array()){

  // get all table rows$trs = $table->getElementsByTagName('tr');  

  // assume first TR is the table header$head = $trs->item(0);

  // find cell names and their index$keys = array();
  foreach($head->childNodes as$th)
    if(!($thinstanceof DomText))
      $keys[] = trim($th->nodeValue);

  if($invalidKeys = array_diff(array_keys($conditions), $keys))
    thrownewException(sprintf('Non-extistent key(s) in table: ', implode(', ', $invalidKeys)));

  // find the row that meets all conditions$targetRow = null;
  foreach($table->childNodes as$tr){

    // internal counter because we can't rely on DOM index$idx = 0;
    foreach($tr->childNodes as$td){

      if($tdinstanceof DomText)
        continue;

      $value = trim($td->nodeValue);

      // check if all conditions matchif(array_key_exists($keys[$idx], $conditions))
        $targetRow = ($value != $conditions[$keys[$idx]]) ? null : $tr;

      $idx++;    
    }

    // stop if we found a matchif($targetRow)
      break;
  }

  if(!$targetRow)
    thrownewException('No row matches your conditions');

  // build an array with row cells$values = array();
  $idx = 0;
  foreach($targetRow->childNodes as$td)
    if(!($tdinstanceof DomText))
      $values[$keys[$idx++]] = trim($td->nodeValue);

  // return the cell value if a specific cell was requestedif($cellName !== null)
    returnisset($values[$cellName]) ? $values[$cellName] : null;

  // otherwise return all values from the matched rowreturn$values;
}

It uses DomDocument because the question wasn't tagged as

@OP: in your case you would use it like:

$html = file_get_contents('http://www.arifoorum.com/test/html.htm');

$dom = new DomDocument();
$doc->preserveWhiteSpace = false;
$dom->loadHtml($html);

$table = $dom->getElementsByTagName('table')->item(0);

print getCellValue($table, 'V_V', array(
  'mõõdikud' => '01',
  'Name 2'   => 'külm',
));

Post a Comment for "Extract Cell Value From Table Based On Another Cells Value"