从PHP CSV中的URL/Link下载图像


Download Image from URL/Link in the CSV in PHP

我有一个CSV列表,其中包含一些图像的URL/链接。

所以我尝试了下面的代码;

if (($handle = fopen($csv_file, "r")) !== FALSE) {
    fgetcsv($handle); 
    $num = count($data);
    for ($c=0; $c < $num; $c++) {
       $col[$c] = $data[$c];
    }
    col1 = $col[0];
    for ($i = 0; $i < count($col1); $i++){
      if ( !$col1[$i] == null){  
          echo $col1[$i]. ",<br>";   
          file_put_contents("images/img.jpg", $elements[$i] . "'n", FILE_APPEND);
      }
   }
 }
 fclose($handle);
}

代码正在运行,但它正在替换执行结束时的图像。我只得到一张图片,它是csv&获取错误Max_execution时间。

试试这个。

$handle      = fopen($csv_file, "r");
$destination = 'images/';
if ($handle) {
    while ($columns = fgetcsv($handle)) {
        foreach ($columns as $imageUrl) {
            if (!empty($imageUrl)) {
                file_put_contents(
                    $destination . basename($imageUrl),
                    file_get_contents($imageUrl)
                );
            }
        }
    }
}

它所做的是打开CVS,在其中循环,一次一行,检查图像URL是否为空,下载并将其放入目录。当然,您需要确保PHP有权写入该目录。该代码也不处理图像命名中的冲突,因此进一步的改进是添加一些冲突检测,并在后缀前添加一个计数器。