DOM Parser Foreach

半腔热情 提交于 2019-12-14 02:42:41

问题


Does anyone know why this wouldn't work?

foreach($html->find('tbody.result') as $article) {
    // get retail
    $item['Retail'] = trim($article->find('span.price', 0)->plaintext);
    // get soldby
    $item['SoldBy'] = trim($article->find('img', 0)->getAttribute('alt'));

    $articles[] = $item;
}
print_r($articles);

回答1:


Try this:

$html = file_get_html('http://www.amazon.com/gp/offer-listing/B002UYSHMM');

$articles = array();

foreach($html->find('table tbody.result tr') as $article) {
  if($article->find('span.price', 0)) {
    // get retail
    $item['Retail'] = $article->find('span.price', 0)->plaintext;
    // get soldby
    if($article->find('img', 0)) $item['SoldBy'] = $article->find('img', 0)->getAttribute('alt');
    $articles[] = $item;
  }

}

print_r($articles);



回答2:


It seems to me the original code should work. But simple_html_dom often breaks or behaves unpredictably.

I recommend using php's built-in DomXPath:

$dom = new DOMDocument;
@$dom->loadHTMLFile('http://www.amazon.com/gp/offer-listing/B002UYSHMM');
$xpath = new DOMXPath($dom);

$articles = array();
foreach($xpath->query('//tbody[@class="result"]') as $tbody){
    $item = array();
    $item['Retail'] = $xpath->query('.//span[@class="price"]', $tbody)->item(0)->nodeValue;
    $item['SoldBy'] = $xpath->query('.//img/@alt', $tbody)->item(0)->nodeValue;
    $articles[] = $item;
}

print_r($articles);


来源:https://stackoverflow.com/questions/7782211/dom-parser-foreach

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