正在使用 PHP 从列表 URL 下载图像到服务器

Downloading Images from list of URL to server using PHP

我制作了一个简单的脚本,可以从 URL 下载图像。它非常有效。

$img_link = 'https://samplesite.com/image.jpg';
$imge_title = basename($img_link);


$ch = curl_init($img_link);
$fp = fopen("folder/".$imge_title, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
?>

接下来要做的是从 txt 文件下载 URLS 的列表并逐行处理它们。

https://samplesite.com/image_1.jpg
https://samplesite.com/image_2.jpg
https://samplesite.com/image_3.jpg
https://samplesite.com/image_4.jpg
https://samplesite.com/image_5.jpg

这是我想出的:

$lines = file( 'List.txt' ); //the list of image URLs

foreach ( $lines as $line ) {
$img_link = $line;
$imge_title = basename($img_link); //I want to retain the original name of the file


$ch = curl_init($img_link);
$fp = fopen($imge_title, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
}

它不起作用,我不断收到警告:

Warning: fopen(image_1.jpg): failed to open stream: No such file or directory
Warning: curl_setopt(): supplied argument is not a valid File-Handle resource
Warning: fclose() expects parameter 1 to be resource

As the file doc says,文件的换行符保留在结果数组中:

Each element of the array corresponds to a line in the file, with the newline still attached.

FILE_IGNORE_NEW_LINES flag 传递给 file(...) 调用。

否则,大部分或所有 $line 值将以 '\n''\r' 字符结尾。

你或许还应该通过 FILE_SKIP_EMPTY_LINES

$lines = file( 'List.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES ); //the list of image URLs