t.bkh t.bkh - 26 days ago 13
JSON Question

how to use file_put_contents function into loops?

I want to get multi images from their urls and I want to save them in a directory.
I've used

file_put_contents()
as you see.but it just puts one of the images.
Is it a better way to us this function in loops or is it another function to use instead of
file_put_contents()
in loop?

<?php
include "config.php";
//open ssl:
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
),
);
set_time_limit(0);

$url = 'https://www.instagram.com/' . $name . '/media/';
$content = file_get_contents($url, false, stream_context_create($arrContextOptions));
$json = json_decode($content, true);
//var_dump($json);die();


mkdir($name);
chmod($name, 0600);
for ($i = 0; $i <= 19; $i++) {
$a = $json['items'][$i]['images']['thumbnail']['url'];
$content = file_get_contents($a);
file_put_contents($name . '/image.jpg', $content);
}
?>

Answer Source

Change the filename to:

file_put_contents($name. '/image_'.$i.'.jpg', $content);

Then they will stop overwriting each other.