Как напечатать ячейки таблицы с простым HTML домом - PullRequest
8 голосов
/ 19 июля 2010

У меня есть этот HTML-код.Я использую Simple HTML Dom для анализа данных в моем собственном php-скрипте.

<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>

Мне нужно получить текст внутри TD в массиве, пример:

$ array [0]= массив («Грег Хаус», «Век Сити»);$ array [1] = array ('Dexter Morgan', 'Miami');

Я пробовал несколько способов получить это, но у меня не получилось в каждом из них.Кто-нибудь может мне помочь?

Ответы [ 3 ]

14 голосов
/ 19 июля 2010

Это должно сделать:

// 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);
3 голосов
/ 18 марта 2015

Это будет работать .. попробуйте это

 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);

Вы можете получить данные из любого тега html, даже атрибутов ...

1 голос
/ 25 января 2013

@ lucia nie

Вы должны сделать это так:

// 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);
...