我制作了一个简单的脚本,可以从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