2

I am working on API that return single currency record in one request. One request take 0.5-1 sec to response, and 15 requests take 7-15 seconds.

As i know server can manage 100s of request per seconds. I want to hit 15 request on server at once so server will give response in 1-2 seconds not in 15 Seconds. Return all data in one single array to save my loading time.

Check my Code

I am using Loop, loop wait until previous curl request not complete. How can i say to loop, keep continue and dont wait for response.

$time_Start = microtime(true);

$ids = array(1,2,11,15,20,21); // 6 ids in demo, 15+ ids in real
$response = array();
foreach ($ids as $key => $id) {
    $response[$id] = get_data($id);
}

echo "Time: ". (microtime(true)-$time_Start)."sec";
// output 5 seconds on 6 request


function get_data($id){
    $fcs_api_key = "API_KEY";
    $ch=curl_init();
    curl_setopt($ch,CURLOPT_URL,"https://fcsapi.com/api/forex/indicators?id=".$id."&period=1d&access_key=".$fcs_api_key);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $buffer = curl_exec($ch);
    curl_close($ch);

    return $buffer;
}
Faisal Abbas
  • 71
  • 1
  • 6

1 Answers1

1

You can use PHP multi curl https://www.php.net/manual/en/function.curl-multi-init.php

Below I write a code that open Parallel request.

$time_Start = microtime(true);

$ids = array(1,2,3,4,5,6); // You forex currency ids.
$response = php_curl_multi($ids);

echo "Time: ". (microtime(true)-$time_Start)."sec";
// Time: 0.7 sec

Function

function php_curl_multi($ids){
    $parameters = "/api/forex/indicators?period=1d&access_key=API_KEY&id="; // ID will set dynamic
    $url        = "https://fcsapi.com".$parameters;

    $ch_index = array(); // store all curl init
    $response = array();

    // create both cURL resources
    foreach ($ids as $key => $id) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,  $url.$id);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $ch_index[] = $ch;
    }

    //create the multiple cURL handle
    $mh = curl_multi_init();

    //add the handles
    foreach ($ch_index as $key => $ch) {
        curl_multi_add_handle($mh,$ch);
    }

    //execute the multi handle
    do {
        $status = curl_multi_exec($mh, $active);
        if ($active) {
            curl_multi_select($mh);
        }
    } while ($active && $status == CURLM_OK);

    //close the handles
    foreach ($ch_index as $key => $ch) {
        curl_multi_remove_handle($mh, $ch);
    }
    curl_multi_close($mh);


    // get all response
    foreach ($ch_index as $key => $ch) {
        $response[] = curl_multi_getcontent($ch);
    }

    return $response;
}
asad app
  • 321
  • 1
  • 2
  • 14