2011-10-12 74 views
4

所以我想抓住从其他网站的一些图片来自多个页面下载图片,问题是每个图像是在不同的页面抓斗/使用PHP preg_match_all和卷曲

IE:ID/1,ID/2,ID/3等等等等

到目前为止我有下面的代码可以抓住使用给出从单个URL的图像:

$returned_content = get_data('http://somedomain.com/id/1/'); 

但需要使线的上方成为阵列(I猜),所以它会从第1页抓取图像,然后继续抓取第2页上的下一个图像,然后第3页等等tomatically

function get_data($url){ 
$ch = curl_init(); 
$timeout = 5; 
    curl_setopt($ch,CURLOPT_URL,$url); 
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout); 
    curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13'); 
$data = curl_exec($ch); 
    curl_close($ch); 
return $data; 
} 

$returned_content = get_data('http://somedomain.com/id/1/'); 

if (preg_match_all("~http://somedomain.com/images/(.*?)\.jpg~i", $returned_content, $matches)) { 

$src = 0; 
     foreach ($matches[1] as $key) { 

if(++$src > 1) break; 

      $out = $key; 
     } 

     $file = 'http://somedomain.com/images/' . $out . '.jpg'; 


$dir = 'photos'; 

$imgurl = get_data($file); 

file_put_contents($dir . '/' . $out . '.jpg', $imgurl); 

echo 'done'; 
} 

一如既往,所有的帮助表示感谢,并提前致谢。

+0

你真的确定你想使用PHP吗?并不是说这是不可能的,但最终取决于你想要做什么,你可能会遇到很多问题,这些问题通常是半自动更好地解决的。 – hakre

+0

PHP是目前我知道的唯一代码(ex html,css),最终的结果就是为我自己下载几张图片以便稍后浏览,但是这里有大约100张图片,我不想访问每个页面“点击右键>>另存为“。 – Dizzi

+0

您正在使用哪种操作系统? – hakre

回答

4

这非常令人困惑,因为它听起来像你只对每页保存一个图像感兴趣。但是,这段代码使得它看起来像你实际上试图保存每个页面上的每个图像。所以完全有可能我完全误解了......但是这里就是这样。

循环每页面并不难:

$i = 1; 
$l = 101; 

while ($i < $l) { 
    $html = get_data('http://somedomain.com/id/'.$i.'/'); 
    getImages($html); 
    $i += 1; 
} 

下再假设你想将特定页面上保存所有图像:

function getImages($html) { 
    $matches = array(); 
    $regex = '~http://somedomain.com/images/(.*?)\.jpg~i'; 
    preg_match_all($regex, $html, $matches); 
    foreach ($matches[1] as $img) { 
     saveImg($img); 
    } 
} 

function saveImg($name) { 
    $url = 'http://somedomain.com/images/'.$name.'.jpg'; 
    $data = get_data($url); 
    file_put_contents('photos/'.$name.'.jpg', $data); 
} 
+0

我实际上已经得到了我的foreach循环工作我只需要将我的代码稍微移动一下,但是你的工作并且很多清洁感谢! – Dizzi