简体   繁体   中英

Calling API inside the loop using php

I looking for any best and fastest way to call API inside the loop for example bellow is my current code but I don't think that is the good way because in this way API is being called 100s of time because it's under the php loop. Is there anyway I can use it outside ? but the problem is I have to pass some unique values which are only in loop.

$sql_q = sqlsrv_query($mssql, "SELECT * FROM Table WHERE Club='123'");
   while($sql_f = sqlsrv_fetch_array($sql_q)){
        
    / Calling API TO Check Status
    $auth = curl_init();
    curl_setopt_array($auth, array(
    CURLOPT_URL => "http://api.checkstatus.com/apiurl",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "POST",
    CURLOPT_POSTFIELDS =>"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\r\n  <soap:Body>\r\n    <CheckStatus xmlns=\"http://apiurl.info/\">\r\n      <UserID>".$ql_f['ID']."</UserID>\r\n </CheckStatus >\r\n  </soap:Body>\r\n</soap:Envelope>",
    CURLOPT_HTTPHEADER => array(
    "Content-Type: text/xml"
    ),
    ));
    $authres = curl_exec($auth);
    curl_close($auth);
    
    }

You need to set up a scheduling mechanism

For example:

  1. Create a queue of IDs to be passed to the API (a MySQL table would do)
  2. Write a script that takes the first item from the queue and makes the API call.
  3. After the call, remove the ID from the queue or mark it as done
  4. Use eg cron to schedule how often the script gets called
  5. Create another script that manages the queue according to your business logic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM