Reputation: 101
I need to call cURL multiple times to get different JSON responses so I followed the code in the answer of this question: Multiple curl json and json print.
Now I realize that the variable that stores the return data is only holding the information from the last URL in the array (it's been overwritten). Here is my code:
$urls = Array(
'https://example.com/projects/277199/roles.json',
'https://example.com/projects/292291/roles.json'
);
foreach ($urls as $key=>$url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "XXX:YYY");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_response = curl_exec($ch);
curl_close($ch);
$rolesData = json_decode($ch_response,true);
}
print_r($rolesData); //It's only printing the data from the last element in the urls array
How do I correctly store the data?
Upvotes: 1
Views: 57
Reputation: 5250
just add []
or [$key]
to $rolesData
foreach ($urls as $key=>$url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "XXX:YYY");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ch_response = curl_exec($ch);
curl_close($ch);
$rolesData[] = json_decode($ch_response,true);
}
print_r($rolesData);
Upvotes: 1