How to rename files into a list. CSV in your output with PHP and CURL?

Asked

Viewed 200 times

1

How are you all? This is my first post because I am a beginner with PHP and CURL and I needed to create a script to download several images in repositories through a file .csv. It reads the url where the file is, and saves in a pre-established directory, I use the "basename" function to recover the name of the image that is in the URL. Until then the script does everything smoothly saves the right images everything correctly, but I can’t change this output to rename the files as needed. I wonder if I can use the same. csv add one more column, or insert in the script the specific names for each image, that is, I already know what this name would be and the order to rename would be the one in the . CSV, look at the script:

<?php

$csvFile = file('imagensuno.csv'); // Aqui ele pega o arquivo .csv com as URL das imagens 

foreach ($csvFile as $line) {

  $url = str_getcsv($line);

  $ch = curl_init($url[0]);

  $name = basename($url[0]); //Aqui ele usa o nome da imagens na URL para salvar ela com o nome que ela tem na URL


if (!file_exists('G:\cca_imagens/' . $name)) {
    $fp = fopen('G:\cca_imagens/' . $name, 'wb');

  }

  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_exec($ch);
  curl_close($ch);
  fclose($fp);

  //echo str_getcsv($line);

}

the function str_getcsv, I will scroll down the line of the csv file "imagensuno.csv" which is located in the same directory as the script.

to file_exists which will check whether the image has been saved before, very useful if script execution is stopped.

Also note the use of the function basename to recover the name of the image that is in the URL.

And this is where my doubt is, and I can’t remember if I can or can make you save the name I need that would be:

Ex of file . csv

Coluna 1                                        Coluna 2
https://enderecodaimagens.com.br/img/foto.png,  foto.png => sku435.png, 
https://enderecodaimagens.com.br/img/foto2.png, foto2.png => sku444.png, 
https://enderecodaimagens.com.br/img/foto3.png  foto.png => sku865.png

How would they all be in the same. csv I want to rename these not by URL name but by Column 2 action, but I don’t know if it’s possible, I can’t think of how to do this output.

People need this Help and if someone wants to use the script this the layout and logico want to improve it also think very good ok?

abs

  • The file 'imagensuno.csv' is the file that holds the two columns, and you want to select the image related to column 1 and rename with column name 2, that’s it ?

  • Yes, or if I can do this another way. I think of . csv so that everything stays in one run and file, because on average this will occur with on average 25000 images

2 answers

0

Renamed file: '.$Rename.'
-
'; //Tests if the file exists if (!file_exists('C: wamp www projects dw photo cca/' . $name)) { //Test to rename the file if(Rename("C: wamp www projects dw photo cca $name", "C: wamp www projects dw photo cca $Rename"){ echo 'Original file: '.$name. '
Renamed file: '.$Rename.'
Status: Successfully renamed, line '.$Count.'
'; }Else{ echo 'Original file: '.$name. '
Renamed file: '.$Rename.'
Status: Error renaming, line '.$Count.'
'; } } $Count +=1; } ?>

This above edited code!

  • When you need to add some information to the question, click edit and put together in the previous question, the place of answers is only for answer, take a tour to better understand how the site works: https://answall.com/tour

0

Assuming you have one .csv in the following format:

http://127.0.0.1/stack/fopencsv/imagem1.jpg, novaimagem1.jpg
http://127.0.0.1/stack/fopencsv/imagem2.jpg, novaimagem2.jpg
http://127.0.0.1/stack/fopencsv/imagem3.jpg, novaimagem3.jpg
http://127.0.0.1/stack/fopencsv/imagem4.jpg, novaimagem4.jpg
http://127.0.0.1/stack/fopencsv/imagem5.jpg, novaimagem5.jpg

You can rename using the function name php, and fgescsv with the following script:

<?php

//Abrindo o manipulador
$handle = fopen('csv.csv', 'r');

$count = 1;
$file = fgetcsv($handle);
//Abrindo o arquivo e lendo as linhas
while ($row = fgetcsv($handle)) {
    //removendo a url (url não é aceita no 'rename')
    $name = str_replace('http://127.0.0.1/stack/fopencsv/img/','',$row[0]);
    $rename = $row[1];

    echo 'Arquivo original: ' . $name . '<br>Arquivo renomeado: ' . $rename . '<br>-<br>'.PHP_EOL;
    //Testa se o arquivo existe
    //use __dir__ , ou outra coisa, o importante é apontar o local correto do arquivo, dentro do mesmo servidor.
    if (!file_exists(__DIR__ . '\\' . $name)) {
        //Teste para renomear o arquivo
        if (rename(__DIR__ . '\img\\' . $name, __DIR__ . '\img\\' . $rename)) {
            echo 'Arquivo original: ' . $name . '<br>Arquivo renomeado: ' . $rename . '<br>Status: Renomeado com sucesso, linha ' . $count . '<br>';
        } else {
            echo 'Arquivo original: ' . $name . '<br>Arquivo renomeado: ' . $rename . '<br>Status: Erro ao renomear, linha ' . $count . '<br>';
        }
    }
    $count += 1;
}

Rules:

1 - Files must be on the same server from where the script is executed.

2 - Replace the url where the file is by the local path.

3 - My files are in the folder: Script: c: xampp htdocs stack fgetscsv Images: c: xampp htdocs stack fgetscsv img

4 - Give permission to the file (probably already ok)

  • The script will rename the "images" in the . CSV itself?

  • No, this script will rename the images even, you want to rename csv ?

  • Sorry for the delay, the several god Warnings script:

  • Warning: fopen() expects at least 2 Parameters, 1 Given in directory muda.php on line 4

  • Warning: fgetcsv() expects Parameter 1 to be Resource, Boolean Given in directory muda.php on line 8

  • I’m looking to adjust!

  • The first message of fopen is because you need to indicate how the file will be opened, enter 'r', and the second error is because your fopen did not open the file, edit the question with the code of this error

  • Thus: $Handle = fopen('imagensrename.csv','r');

  • You are on linux or windows ?

  • Now errors only in 2 lines: Warning: Rename(C: wamp www projects dw photo cca$name,C: wamp www projects dw photo cca$Rename): The system cannot find you

  • Alias using Windows!

  • @Andersonlegimenes did not test this script, I will test here already update the answer

  • Okay, I’ll hold on!

  • @Andersonlegimenes see if you can now apply, this script worked, the images were renamed, pay attention to the issue of the url in the name, Rename will not understand, then has a str_replace to remove..

  • After a battle with health, I returned I apologize for not returning earlier but was unable even. Well I did not advance in the code, the errors continue in the script you passed, my download the URL images and names with the name that it has in the link. But I still can’t rename them as needed. How can I pass the code now to someone else to help me, I’m lost.

Show 10 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.