php for循环获取每个URL地址

时间:2016-04-29 13:02:45

标签: php

我坚持使用PHP for循环来获取每个URL地址。我非常感谢你的帮助。

URL就像这样增加1:

http://www.4hb.com/letters/index.html
http://www.4hb.com/letters/index1.html
http://www.4hb.com/letters/index2.html
http://www.4hb.com/letters/index3.html

这是我的代码:

for ($i=1;$i<3;$i++) {
    $url="http://www.4hb.com/letters/index".$i.".html";
    include 'class.snoopy.php';
    $s=new snoopy;
    $s->fetch($url);
    $txt=$s->results;
}

2 个答案:

答案 0 :(得分:0)

也许你忘了}?此外,include可以退出循环。

include 'class.snoopy.php';
$urls = [];

for ($i=1; $i<3; $i++) {
    $url="http://www.4hb.com/letters/index".$i.".html";
    $s = new snoopy();
    $s->fetch($url);
    $urls[] = $s->results;
}

print_r($urls);

答案 1 :(得分:0)

使用您的代码,第一个循环只能有$ i = 1,第二个循环只有$ i = 2,然后循环停止。所以你得到:

http://www.4hb.com/letters/index1.html
http://www.4hb.com/letters/index2.html

改变你的循环:

for($i=0;$i<4;$i++){
    if ($i==0){
        $url="http://www.4hb.com/letters/index.html";
    }
    else {
        $url="http://www.4hb.com/letters/index".$i.".html";
    }
    include 'class.snoopy.php';
    $s=new snoopy;
    $s->fetch($url);
    $txt=$s->results;
}

我不确定你的问题在哪里,但这解决了循环问题:)