Retrieve data from the first td in every tr

China☆狼群 提交于 2020-01-05 06:59:50

问题


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

回答1:


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



回答2:


simple html dom is a turd. It's simpler to use the built in dom functions and xpath:

$dom = new DOMDocument();
@$dom->loadHTMLFile($url);
$xpath = new DOMXPath($dom);

foreach($xpath->query('//td[1]') as $td){
  echo $td->nodeValue;
}

That said, I would probably still prefer to use phpquery



来源:https://stackoverflow.com/questions/14080986/retrieve-data-from-the-first-td-in-every-tr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!