how to print cells of a table with simple html dom
Asked Answered
R

3

8

i have this html code. Im using Simple HTML Dom to parse the data into my own php script.

<table>
    <tr>
        <td class="header">Name</td>
        <td class="header">City</td>
    </tr>
    <tr>
        <td class="text">Greg House</td>
        <td class="text">Century City</td>
    </tr>
    <tr>
        <td class="text">Dexter Morgan</td>
        <td class="text">Miami</td>
    </tr>
</table>

I need to get the text inside the TDs in an array, example:

$array[0] = array('Greg House','Century City'); $array[1] = array('Dexter Morgan','Miami');

I've tried several ways to get that but i've fail in each and everyone of them. Can someone give me a hand?

Ranitta answered 18/7, 2010 at 23:38 Comment(2)
You should use DOM and XpathRoseola
i have to do it using Simple HTML Dom ;)Ranitta
N
14

This should do:

// get the table. Maybe there's just one, in which case just 'table' will do
$table = $html->find('#theTable');

// initialize empty array to store the data array from each row
$theData = array();

// loop over rows
foreach($table->find('tr') as $row) {

    // initialize array to store the cell data from each row
    $rowData = array();
    foreach($row->find('td.text') as $cell) {

        // push the cell's text to the array
        $rowData[] = $cell->innertext;
    }

    // push the row's data array to the 'big' array
    $theData[] = $rowData;
}
print_r($theData);
Nephralgia answered 18/7, 2010 at 23:45 Comment(1)
@andufo,@Karim, Can you please tell me how you make object($html) in dom object. So you have used it as:- $table = $html->find('#theTable');Bonita
T
7

It will work.. try this

 include('simple_html_dom.php');
 $html = file_get_html('mytable.html');
 foreach($html->find('table tr td') as $e){
    $arr[] = trim($e->innertext);
  }

 print_r($arr);

You can get data from any html tag even attributes too...

Tympany answered 18/3, 2015 at 10:52 Comment(0)
J
2

@lucia nie

You should do this so:

// initialize empty array to store the data array from each row
$theData = array();

// loop over rows
foreach($html->find('#theTable tr') as $row) {

// initialize array to store the cell data from each row
$rowData = array();
foreach($row->find('td.text') as $cell) {

    // push the cell's text to the array
    $rowData[] = $cell->innertext;
}

// push the row's data array to the 'big' array
$theData[] = $rowData;
}
print_r($theData);
Judoka answered 25/1, 2013 at 10:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.