php - 从表格中抓取行,然后抓取单元格

标签 php html simple-html-dom

我正在使用Simple HTML Dom Parser抓取一个表格(如图所示),然后抓取每个 tr。这会将行中的所有项目输出为一个字符串。

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

enter image description here

如何创建一个数组,将数据保存在行中,同时还允许我输出各个单元格?我希望能够说一行中有 7 个单元格(这可以很灵活),并且能够将行中的每个单元格作为变量输出(我需要用这些单元格做其他事情)。


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

最佳答案

就像我在评论中所说的那样,对待行的第一个循环,对于每一行,对待每个单元格的另一个 foreach 。所以基本上你需要两个。

由于没有示例标记,因此没有太多内容可继续,但想法如下:

$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`)
    }
}

旁注:请注意,如果您希望跳过 header ,只需使用计数器和带有 continue 的 if 条件即可。

关于php - 从表格中抓取行,然后抓取单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51038434/

相关文章:

javascript - 如何从填充有 JSON 数据的下拉列表中获取选择的详细信息?

javascript - 从 php 中按谷歌地图 api 中的城市名称自动填充州和国家/地区

php - 结果的 var_dump 给出空值。但更深入的检查返回一个整数

javascript - 禁用选择标签,并使用 angularjs 和 ng-repeat 从另一个选择标签中选择选项

php - CSS 导致 SQL INSERT 执行两次

html - 页脚不显示或粘在底部 - 隐藏在导航后面,z-index 不工作

PHP 简单 HTML DOM 解析器 : Select only DIVs with multiple classes

php - 如何将 simple_html_dom 对象转换回字符串?

php - 拉拉维尔 : Parameterized query with IN() function only returns first in match

javascript - 结合 php 变量和 js 参数