-3

到目前为止我有这个

<?PHP include('simple_html_dom.php');
$html = file_get_html('http://www.mangastream.com/');
foreach($html->find('.side-nav') as $t)
foreach($t->find('a')as $k)
echo $k->href . '<br>'; 
?>

它输出类内部的所有链接。但我只想拥有前 5 个链接。

4

2 回答 2

0

find() returns an array, you can do a single find operation instead of two, and you can slice an array to the first five elements by using array_slice.

This allows you to get the first five element easily:

$ks = $html->find('.side-nav a');
foreach (array_slice($ks, 0, 5) as $k)
    echo $k->href, '<br>'
;

However I suggest you take the DOMDocument based HTML parser - perhaps in compbination with SimpleXML so that you can run xpath queries on the document instead.

于 2013-08-25T14:23:49.197 回答
-2

试试看

<?PHP include('simple_html_dom.php');
$html = file_get_html('http://www.mangastream.com/');
foreach($html->find('.side-nav') as $t){
    foreach($t->find('a')as $key => $k){
        echo $k->href . '<br>';
        if($key >= 4){
            break;
        }
    }
}
?>
于 2013-08-25T14:12:25.747 回答