php 如何使用简单的 html dom 打印表格的单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3277687/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:12:25  来源:igfitidea点击:

how to print cells of a table with simple html dom

phphtml-parsingsimple-html-dom

提问by Andres SK

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

我有这个 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>

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

我需要在数组中获取 TD 中的文本,例如:

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

$array[0] = array('Greg House','Century City'); $array[1] = array('德克斯特摩根','迈阿密');

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

我尝试了几种方法来获得它,但我在每个方法中都失败了。有人可以帮我一把吗?

回答by karim79

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

回答by gsanthosh91

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

您也可以从任何 html 标签甚至属性中获取数据...

回答by koshin

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