繁体   English   中英

使用 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

正如file文档所说,文件的换行符保留在结果数组中:

数组的每个元素对应于文件中的一行,换行符仍然附加。

FILE_IGNORE_NEW_LINES标志传递给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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM