2015-01-26 51 views
0

我目前正在使用PHP簡單的HTML DOM解析器試圖刮一個網站。以下是我迄今爲止:PHP簡單的HTML DOM解析器返回所有列表項

$html = file_get_html('https://www.example.com'); 

// Find all article blocks 
foreach($html->find('.plan') as $article) { 
    $item['title']  = $article->find('.price', 0)->plaintext; 
    $item['intro'] = $article->find('li', 0)->plaintext; 
    $item['details'] = $article->find('.button', 0)->href; 
    $articles[] = $item; 
} 

print_r($articles); 

上述工作正常,但是如果超過一個<li>存在它只返回第一個<li>錯過了休息。

有沒有辦法我可以得到所有列表項?

回答

0

使用查找函數中的第二個屬性,可以定義結果的第n個元素,該元素應返回。在您的示例中,$article->find('li',0)爲您提供索引爲0(所以第一個)匹配元素的li元素。

如果希望所有<li>元素,試試這個:

$html = file_get_html('https://www.example.com'); 

// Find all article blocks 
foreach($html->find('.plan') as $article) { 
    $item['title'] = $article->find('.price', 0)->plaintext; 
    $item['intro'] = array(); //define as array 
    foreach ($article->find('li') as $li) { //get all <li>-elements as array 
     $item['intro'][] = $li->plaintext; //add the plaintext of each single <li> element as new position to the $item['intro'] array 
    } 
    $item['details'] = $article->find('.button', 0)->href; 
    $articles[] = $item; 
} 

print_r($articles); 
相關問題