Search code examples
phphtmlsimple-html-dom

Grab rows and then cells from a table


I'm using the Simple HTML Dom Parser to grab a table (in the image) and then grab each tr. This outputs all the items in the row as one string.

$contents = $html->find('div[class=product-table]', 0);
$titles = $contents->find('tr');

enter image description here

How can I create an array that keeps the data in rows but also allows me to output the individual cells? I want to be able to say there's 7 cells in a row (this could be flexible) and be able to output each individual cell in the row as variables (I need to do other stuff with these).


// Product Code Titles
$contents = $html->find('div[class=product-table]', 0);
$data = array();
$rows = $contents->find('tr');
$counter = 1;
foreach ($rows as $key_row => $row) {
    // process rows here
    foreach ($row->find('td') as $key_cell => $cell) {
      $field_key = "field_5ae0882f9d6f9";
      $data[] = array(
        "column_title" => strip_tags($cell->innertext),
      );
      $counter++;

        // process each cell on the current row iteration
        // or whatever you need to do in each cell (calculations and whatnot)
        // $data[] = then push it inside an array (you can prolly use the keys and use it in `$data`)
    }
} ?>
<pre>
<?php print_r($data); ?>
</pre>
<?php update_field( $field_key, $data, $post_id );

Solution

  • Just like what I've said in the comments, treat the first loop for the rows, and for each row, another foreach for each cell. So basically you need two.

    There's not much to go on since you don't have a sample markup, but here's the idea:

    $data = array();
    $rows = $contents->find('tr');
    foreach ($rows as $key_row => $row) {
        // process rows here
        foreach ($row->find('td') as $key_cell => $cell) {
            // process each cell on the current row iteration
            echo $cell->innertext;
            // or whatever you need to do in each cell (calculations and whatnot)
            // $data[] = then push it inside an array (you can prolly use the keys and use it in `$data`)
        }
    }
    

    Sidenote: Take note, if you want the header to be skipped, just use a counter and an if condition with continue, then you're good to go.