2011-10-16 11 views
1

有誰知道爲什麼這不起作用?DOM Parser Foreach

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); 
+0

什麼是HTML解析器你使用? – imm

+0

簡單的HTML DOM解析器 – Reg

+0

你試圖解析什麼URL? – ghbarratt

回答

1

試試這個:

$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); 
+0

它由於某種原因兩次增加了第一個零售店。 – Reg

0

在我看來,原來的代碼應該工作。但是simple_html_dom經常打破或行爲不可預測。

我建議使用PHP的內置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);