Home > front end >  php rename files when downloading
php rename files when downloading

Time:05-17

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

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_"

CodePudding user response:

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

  •  Tags:  
  • php
  • Related