简体   繁体   中英

Download Image from URL/Link in the CSV in PHP

I have a CSV list which contains URL/Link of some image.

So I had tried this below code;

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);
}

the code is working, but it's replacing the image at the end of execution I'm getting only one pic which's Last row of csv & Getting error Max_execution time.

Try this out.

$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)
                );
            }
        }
    }
}

What it does is open the CVS, loops through it, row at a time, checks that the image URL isn't empty, downloads it and puts it into your directory. You of course need to make sure that PHP has the rights to write to that directory. The code also doesn't handle conflicts in the naming of images, so a further improvement would be to add some clash detection and append a counter before the suffix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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