I have used postman to execute curl request and get response from the api. Everything is working perfectly. But as soon as I try to execute same curl within a php while loop. It doesn't works at all.
Searched over the internet but did not found any useful information. I would like to know if there is any other way, other than using curl. I also tried sleep(3) function from php which sleeps loop for 3 seconds but it didn't helped.
Bottom line curl is not working in php loop whereas it works independently.
Below is my code for reference
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
I tried putting curl init and other setopt before the while loop, but it is not working either.
$curl = curl_init();
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_ENCODING, "");
curl_setopt($curl, CURLOPT_MAXREDIRS, 10);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($curl, CURLOPT_POSTFIELDS, "");
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
"Authorization: Bearer 78654356gvgfdr43wsdxcfg",
"cache-control: no-cache"
));
while (($company = fgets($handle)) !== false) {
// process the line read.
$company = trim($company);
if(!empty($company)) {
curl_setopt($curl, CURLOPT_URL, https://api.domain.com/services/v3/api/entities?search-term=$company&page-size=10000);
$response = curl_exec($curl);
$err = curl_error($curl);
$response_array = json_decode($response, TRUE);
$items = $response_array['items'];
if (!empty($items)) {
foreach ($items AS $item) {
$tt_id = $item['tt_id'];
$tt_Name = $item['tt_Name'];
$tt_TypeID = $item['tt_TypeID']['id'];
//save to db
}
}
}
}
curl_close($curl);