我正在使用Simple HTML Dom Parser抓取一个表格(如图所示),然后抓取每个 tr
。这会将行中的所有项目输出为一个字符串。
$contents = $html->find('div[class=product-table]', 0);
$titles = $contents->find('tr');
如何创建一个数组,将数据保存在行中,同时还允许我输出各个单元格?我希望能够说一行中有 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/