PHP简单的HTML DOM解析器返回所有列表项

问题描述:

我目前正在使用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>错过了休息。

有没有办法我可以得到所有列表项?

使用查找函数中的第二个属性,可以定义结果的第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);