是否可以限制此循环..只需要四个循环?
我在另一篇文章中得到了这个来源并且它正在工作,但我只需要限制循环
$scraper = new DOMScraper();
$scraper->setSite('http://anywebsite.com/testig12.aspx')->setSource();
Class DOMScraper extends DOMDocument{
public $site;
private $source;
private $dom;
function __construct(){
libxml_use_internal_errors(true);
$this->preserveWhiteSpace = false;
$this->strictErrorChecking = false;
}
function setSite($site){
$this->site = $site;
return $this;
}
function setSource(){
if(empty($this->site))return 'Error: Missing $this->site,
use setSite() first';
$this->source = $this->get_data($this->site);
return $this;
}
function getInnerHTML($tag, $id=null, $nodeValue = false){
if(empty($this->site))return 'Error: Missing $this->source,
use setSource() first';
$this->loadHTML($this->source);
$tmp = $this->getElementsByTagName($tag);
$ret = null;
foreach ($tmp as $v){
if($id !== null){
$attr = explode('=',$id);
if($v->getAttribute($attr[0])==$attr[1]){
if($nodeValue == true){
$ret .= trim($v->nodeValue);
}else{
$ret .= $this->innerHTML($v);
}
}
}else{
if($nodeValue == true){
$ret .= trim($v->nodeValue);
}else{
$ret .= $this->innerHTML($v);
}
}
}
return $ret;
}
function innerHTML($dom){
$ret = "";
$nodes = $dom->childNodes;
foreach($nodes as $v){
$tmp = new DOMDocument();
$tmp->appendChild($tmp->importNode($v, true));
$ret .= trim($tmp->saveHTML());
}
return $ret;
}
function get_data($url){
if(function_exists('curl_init')){
$ch = curl_init();
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}else{
return file_get_contents($url);
}
}
}
?>
然后在这里我想限制显示因为它不会废弃该网站的所有数据,如2000条记录..我只想加载最新的4
<?php echo '<div>'.$scraper->getInnerHTML('div','id=LeftDiv12').'</div>'; ?>
谢谢
答案 0 :(得分:2)
只需使用这样的虚拟计数变量:
$Count = 0;
foreach($Array as $Key => $Value){
//your code
$Count++;
if ($Count == 4){
break; //stop foreach loop after 4th loop
}
}
答案 1 :(得分:0)
可以用来限制foreach循环的一种方法是在foreach循环之外创建一个变量,并在每次循环运行时向变量添加一个变量。然后在一定次数后退出循环。我已经修改了你的功能以完成我上面描述的功能。
from bokeh.plotting import figure, output_file, show,hplot
from bokeh.charts import Bar
data2=[65.75, 48.400000000000006, 58.183333333333337, 14.516666666666666]
bar = Bar(values=data2,xlabel="beef,pork,fowl,fish",ylabel="Avg consumtion", width=400)
show(bar)
答案 2 :(得分:0)
不确定您指的是哪个循环,但您可以在循环外创建一个计数器,然后在循环内递增。在计数器上包含一个if语句&gt; = 4
$counter = 0;
foreach($nodes as $v){
if($counter>=4){
break;
}
$tmp = new DOMDocument();
$tmp->appendChild($tmp->importNode($v, true));
$ret .= trim($tmp->saveHTML());
$counter++;}
可能有点笨拙,但它会完成工作。