Copy and rename image

Discussion in 'PHP' started by Fracisc, Mar 18, 2014.

  1. #1
    I have an csv file with two columns, image and name. I need to rename all the images with the new names. What's the easiest way to do that?

    Thanks!
     
    Fracisc, Mar 18, 2014 IP
  2. Vooler

    Vooler Well-Known Member

    Messages:
    1,146
    Likes Received:
    64
    Best Answers:
    4
    Trophy Points:
    150
    #2
    I did not test, but it will work I hope .... will generate new csv file ...

    <?php
         $array = Array();
         $f = fopen("filename.csv", "r");
         while ($row = fgetcsv($f, 1024))
        {
               //$row[0] is first column
               //$row[1] is second column
               $row[1]  = "new file name here";
               $array []= '"'.implode('","', $row);
        }
         file_put_contents('newfile.csv', implode("\n", $array);
    PHP:
     
    Vooler, Mar 20, 2014 IP
  3. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #3
    I would approach it similar to how Vooler did, though I'd use two file handlers for lower memory use rather than building a large array. If the source CSV is really big, that method can bite you. (though it is faster with smaller datasets).

    <?php
    	$inFile = fopen('filename.csv', 'r');
    	$outFile = fopen('newfile.csv', 'w');
    	while ($row = fgetcsv($inFile, 1024)) {
    		$row[1] = 'new file name nere';
    		fputcsv($outFile, $row);
    	}
    	fclose($inFile);
    	fclose($outFile);
    ?>
    Code (markup):
    Though a bit of clarification on "rename all the images" might help us dial in a solution better. That was a bit... vague.
     
    deathshadow, Mar 20, 2014 IP
    Vooler likes this.