目前,我正在抓取一个搜索页面,并试图将其放到只显示4个结果的地方,而不是在搜索页面上显示每个结果。
我的密码在这里。
<?php
$html = file_get_html('http://www.example.com/?s='.$artist.'');
foreach($html->find('div.row > ul > li a') as $element)
{
//echo
$url = ''.$element->href;
$html2 = file_get_html($url);
$image2 = $html2->find('meta[property=og:image]',0);
// print $image2 = $image2->content;
$pure = $image2->content;
$title2 = $html2->find('header.section-header h2 ',0);
$links = $title2->plaintext;
// print $title2 = $title2->plaintext;
print "<li class='album col-md-3 col-sm-6 col-smx-6 col-xs-6 flex' itemprop='itemListElement' itemscope='' itemtype='http://schema.org/MusicAlbum'>
<meta itemprop='url' content='".$url."'>
<meta itemprop='numTracks' content='13'>
<a href='".$url."'>
<img src='".$pure."' alt='".$links."' title='".$links."' itemprop='thumbnailUrl'>
<span class='title'><strong class='artist' itemprop='byArtist'>".$links."</strong></span>
<span class='information'>
</span>
</a>
</li>";
}
?>这个返回的是这样的东西。

但我正试图得到更像这样的结果。

发布于 2016-01-20 04:25:08
使用您自己的代码,只需使用一个计数器(注意不同之处):
<?php
$html = file_get_html('http://www.example.com/?s='.$artist.'');
$i = 0; // begin counter
foreach($html->find('div.row > ul > li a') as $element)
{
if($i > 3) { // this will ensure that you only display 4 results
break;
}
//echo
$url = ''.$element->href;
$html2 = file_get_html($url);
$image2 = $html2->find('meta[property=og:image]',0);
// print $image2 = $image2->content;
$pure = $image2->content;
$title2 = $html2->find('header.section-header h2 ',0);
$links = $title2->plaintext;
// print $title2 = $title2->plaintext;
print "<li class='album col-md-3 col-sm-6 col-smx-6 col-xs-6 flex' itemprop='itemListElement' itemscope='' itemtype='http://schema.org/MusicAlbum'>
<meta itemprop='url' content='".$url."'>
<meta itemprop='numTracks' content='13'>
<a href='".$url."'>
<img src='".$pure."' alt='".$links."' title='".$links."' itemprop='thumbnailUrl'>
<span class='title'><strong class='artist' itemprop='byArtist'>".$links."</strong></span>
<span class='information'>
</span>
</a>
</li>";
$i++; // increment your counter
}
?>发布于 2016-01-20 04:20:28
在循环之前启动一个计数器。
$i=1;然后在每次迭代之后增加它
$i++;然后检查它是否达到4,然后中断。
$i=1;
foreach($test as $value)
{
if($i>4)
break;
//rest of your code here
$i++;
}不,我不会用您的代码更新这个答案,因为这不会是您的学习体验。从长远来看,它只会变成一个复制粘贴作业,对你没有任何帮助。只需重复几遍,然后将这个简单的解决方案应用到您的代码中,您将永远不会忘记它:)
https://stackoverflow.com/questions/34891523
复制相似问题