从每个 tr 的第一个 td 检索数据
问题描述:
我正在抓取一个页面,其中包含一个带有多个 tr 的表格.在每个 tr 中有四个 td,我想从这些 td 中的第一个获取数据.下面是我到目前为止尝试过的代码,但它抓住了所有的 td.我怎样才能完成我想要的?
I'm scraping a page which contains of a table with several tr's. Inside every tr there's four td's, and I want to get the data from the first of these td's. Below is the code I've tried so far, but it grabs all the td's. How can I accomplish what I want?
...
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
foreach($row->find('td', 0) as $cell) {
echo $cell;
}
}
答
想想为什么要使用第二个 foreach
,而实际上你只想对每个 行中的一个元素进行操作代码>.
Think about why you're using the second foreach
when you actually only mean to act on one element within each row
.
$html = new simple_html_dom();
$html = file_get_html($url);
foreach($html->find('table tr') as $row) {
$cell = $row->find('td', 0);
echo $cell;
}