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 = "$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


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


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 ~

Leave a Reply