KPO
KPO

Reputation: 880

How do I select a particular column in a HTML table with no ID?

I am using SimpleHTMLDOM and I have two tables with identical columns and I need to extract the column titles?

Sample Picture

Below is what I am using to get all the data but now I need to only select the Month and corresponding column titles (jan, feb, etc)

 $r_tables = $dom->find('table');

foreach($r_tables as $table) {
    $r_cells = $table->find('td');

    foreach($r_cells as $cell) {
        echo $cell->plaintext.'<br />';
    }
}

Upvotes: 0

Views: 906

Answers (4)

Supericy
Supericy

Reputation: 5896

This should do what you want (If I understand correctly):

foreach($r_tables as $table) {
    $r_cells = $table->find('td');

    echo $r_cells[0]->plaintext . '<br />';;
}

Upvotes: 0

pguardiario
pguardiario

Reputation: 54984

Find the td's from the first tr of the first table:

$tds = $dom->find('table', 0)->find('tr', 0)->find('td');

Map the text of each td into an array:

$headers = array_map(function($td){return $td->text();}, $tds);

Upvotes: 0

Herb
Herb

Reputation: 345

I think what you are looking for is ...

$tables = $dom->find('table');

foreach($tables as $table) {
    $r_cells = $table->find('tr');
    $i = 0;
    foreach($r_cells as $row) {
        $cell = $row->find('td');
        if ($i == 0) {
            foreach($cell as $td) { 
                echo $td.'<br />';
            }
        }  
    $i++;  
    }
}

Upvotes: 1

Herb
Herb

Reputation: 345

a crude way would be

$i = 0;
foreach($r_tables as $table) {
$r_cells = $table->find('td');

foreach($r_cells as $cell) {
  if($i == 0) {    
    echo $cell->plaintext.'<br />';
  }    
}
$i++;

}

Upvotes: 0

Related Questions