Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

php rename files when downloading

Having trouble and keep getting error with my efforts , currently have an array in this format ….

$espn_ar["pid_6254"] = "2977742";
$espn_ar["pid_8269"] = "9614";

I’m using it to create url paths to download some images and name them

foreach ($espn_ar as $value){
    $imageUrl = "https://a.espncdn.com/combiner/i?img=/i/headshots/nfl/players/full/$value.png&h=107&w=80&scale=crop";
    $imageName = "images/mfl_.$value.png";
    $imageFile = file_get_contents($imageUrl);
    file_put_contents($imageName, $imageFile);
}

using the array example above the files are being named

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mfl_2977742.png
mfl_9614.png

But i want the files to be named for the value that follows the "pid_" in each array item , so the file names i want are

mfl_6254.png
mfl_8269.png

Using my example , can anyone show me how to change the value when naming each image to the numbers following "pid_"

>Solution :

Include the keys in your foreach loop and extract the number for your filename

foreach ($espn_ar as $key => $value) {
    $imageName = sprintf('images/mfl_%s.png', str_replace('pid_', '', $key));
  
    // etc
}

Demo ~ https://3v4l.org/FgMi2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading