I am building a function to download images from an external source, and then write the id of each product has been downloaded along with the path to json file,
The download loop is working correctly but when am trying to save the product id & image path to a text file only the first record is saved.
i tried to print the output before using the file_put_contents
function and it turns out am getting the correct result. I am wondering why only the first result is saved not all of them ?
I spent almost all day tryinf to figure it out but no luck. any help will be appreciated.
here is my code:
$url = 'product-test2.json'; // path to JSON file
$data = file_get_contents($url);
$characters = json_decode($data, true);
$i = array_column ($characters , 'Id');
foreach ( $i as $value => $productid){
include 'login.php';
$url = "http://xxxx.com/api/products/image/";
$url .= implode($matches [0]); // get the token form login.php
$url .= '/' . $productid ; //product id
// echo $url . '<br>';
$opts = array ('http' => array (
'methos' => 'GET',
'header' => 'Content-typpe: application/json',
)
);
$context = stream_context_create ($opts);
$urlImage = file_get_contents ($url , false , $context);
$urlImage = substr_replace ($urlImage , "",-1);
$urlImage = substr ($urlImage , 1);
$fopenpath = 'C:\\xampp\htdocs\\test\\api\\images\\' ;
$fopenpath .= $productid . '.jpg';
$fp = fopen ( $fopenpath, 'w');
$c = curl_init ($urlImage);
curl_setopt ($c , CURLOPT_FILE , $fp);
curl_setopt ($c , CURLOPT_HEADER, 0);
curl_setopt ($c , CURLOPT_POST, false);
curl_setopt ($c , CURLOPT_SSL_VERIFYPEER, false);
$rawdata = curl_exec ($c);
fwrite ($fp, $rawdata);
fclose ($fp);
//
$result3= ["id" => $productid ,"image_path" => $fopenpath] ;
$image_file = "images.json";
$output = json_encode ($result3);
print_r ($output);
file_put_contents ($image_file , $output );
};
and here is the result from print_r ($result3);
{"id":2977,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\2977.jpg"} {"id":2981,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\2981.jpg"} {"id":3009,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\3009.jpg"} {"id":3018,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\3018.jpg"} {"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}
as you can see the Print_r is correct all what i want to do is to save the output into file and currently here is the result from file_put_contents only one array :
{"id":11531,"image_path":"C:\\xampp\\htdocs\\test\\api\\images\\11531.jpg"}
can you please help and tell me what am doing wrong i already spend a lot of time on this :)