0

I am trying to scrape table's td tag, but first I need to check th. For example let say table structure is like below.

<tbody>
  <tr>
      <th>color</th>
      <td>red</td>
  </tr>
  <tr>
      <th>price</th>
      <td>23.267$</td>
  </tr>
  <tr>
      <th>brand</th>
      <td>mustang</td>
  </tr>
</tbody>

In this table I need to scrape mustang value. But I can't use $crawler->filter('table td')->eq(3); for that. Because position is always changing. So I need to catch the value by it's th. I mean if th's value is brand then get it's td

what is the best way to this?

tate
  • 49
  • 7

1 Answers1

0

Not sure it's a best solution, but I solved it with this:

$props = $node->filter("table th")->each(function($th, $i){
    return $th->text();
});
$vals = $node->filter("table td")->each(function($td, $i){
    return $td->text();
});

$items = [
    "brand" => "", 
    "color" => "",
];

for ($a=0; $a < count($props); $a++) { 
    switch ($props[$a]) {
        case 'brand':
            $items["brand"] = $vals[$a];
            break;                        
    }
}

If there is another way or much better way to achieve this. Please feel free to post it here. Thank you.

tate
  • 49
  • 7