-1

我正在制作一个将内容(图像)放到我的网站上的爬虫,我制作了一个脚本,可以抓取并将 URL 保存到图像中,但现在我需要将图像上传到我的服务器,以便我可以在我的网站。

我见过有人说应该使用 file_put_contents 但你必须指定图像名称和 ext 但它会是动态的吗?

4

2 回答 2

1

你可以使用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);
于 2012-08-16T17:17:59.633 回答
0

使用file_get_contentsandfile_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);
}

文档

于 2012-08-16T17:20:03.487 回答