Reputation: 51
Im searching for some help with my CurL code. Im trying to execute multiple URLS but it only runs the last results.
Here is my code:
function executeCurl($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($data['url']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute post
$result = curl_exec($ch);
curl_close($ch);
unset($data,$url,$ch);
//close connection
}
Im running the executeCurl in a loop but it only executes the last result.
Upvotes: 2
Views: 4065
Reputation: 1006
It seems like the $result
is the problem.
I'm assuming that the $result is defined globally... and that means,
each time you run the executeCurl()
, the $result
is being overwritten.
Therefore when your loop is done and you take a look at $result
, all you have is the result of your LAST executeCurl()
.
You should return $result, and do whatever you need to do with the result for each loop.
This is a sample code which may help you:
// Add a return to your executeCurl function
function executeCurl($data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, trim($data['url']));
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HEADER, 0);
//execute post
$result = curl_exec($ch);
curl_close($ch);
unset($data,$url,$ch);
//return the result
return $result;
}
// Your loop
$results = array();
for ($i=0;$i<count($dataList), $i++) { // $dataList is whatever your list of datas are
$results[$i] = executeCurl($dataList[$i]);
}
// Check out your results
print_r($results);
Upvotes: 1