多次从URL保存图像

问题描述:

我正在制作一个爬网程序,将内容(图像)放到我的网站上,我已经制作了一个脚本来爬网并将网址保存为图像,但现在我需要将图像上传到我的服务器,以便我可以在我的网站上使用它们。多次从URL保存图像

我见过有人说应该使用file_put_contents,但你必须指定图像名称和分机,但它会动态?

+0

所以你是不是你的网站是在同一台服务器上运行的抓取工具? – Roloc 2012-08-16 17:15:58

+0

如果你正在下载和保存,你应该有你已经下载的名称,所以你可以使用它来上传。或者,您可以上传流式传输,然后漫步您的下载目录,并上传您找到的每个文件。 – ernie 2012-08-16 17:18:12

可以使用file_get_contents()file_put_contents()

$image = 'http://example.org/image.jpg'; 
$filename = basename($image); 
$content = file_get_contents($image); 
file_put_contents('/path/to/your/dir/'.$filename, $content); 

使用file_get_contentsfile_put_contents很可能是最简单的方法。

为了避免碰撞(具有相同名称的文件),可以使文件名的URL部分:

假设URL的数组:

$path = '/path/to/image/folder/'; 
$urls = array(
    'http://www.somesite.no/some_image.jpg', 
    'http://www.someothersite.no/some_other_image.jpg', 
    'http://www.someothersite.no/another_image.jpg' 
); 
foreach ($urls as $url) { 
    $file_content = file_get_contents($url); 
    $filename = preg_replace("/[^a-zA-Z0-9 ]/", "", $url); 
    $filename = str_replace(" ", "-", $filename); 
    file_put_contents($path.$filename, $file_content); 
} 

文档