简体   繁体   中英

Speeding up my PHP curl requests, weather function

function weatherData($date_array){
    $weather_array = [];
    $url = "http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=#######&q=frankston&format=json&date=";
    // Get cURL resource
    array_pop($date_array);
foreach($date_array as $value){
    $url2 = $url . $value;
    $curl = curl_init();
    // Set some options - we are passing in a useragent too here
    curl_setopt_array($curl, array(
        CURLOPT_RETURNTRANSFER => 1,
        CURLOPT_URL => $url2
    ));
    // Send the request & save response to $resp
    $resp = curl_exec($curl);
    // Close request to clear up some resources
    curl_close($curl);
    $data = json_decode($resp);
    $runningTotal = 0;
    for ($i=0; $i < 7; $i++) { 
        $hourly_data = $data->data->weather[0]->hourly[$i]->precipMM;
        $runningTotal += $hourly_data;
    }
    if($runningTotal >= 0.7){
        array_push($weather_array, 'wet <img class="icon" src="images/icons8-Rain-26.png"/>');
    } else{
        array_push($weather_array, 'dry <img class="icon" src="images/images.png"/>');
    }

}
return $weather_array;

Okay, so i have this function that will output an array of weather or not certain dates were 'wet' or 'dry', my problem is if i have maybe 120 dates that i want to do it will take longer than 30 secs in page load time causing a critical error in PHP, so i need some way to bring these synchronous curl requests to some sort of asynchronous form thanks!

ps sorry about that trashy indenting

Note : This is not about speeding up the requests. Taking completely different approach, but it surely solves your PHP timeout error.

Proposed Solution :
It is little wider question. Needs lot of technical explanation and implementation assumptions. I will try to list down main points below:

  1. Don't make any cURL requests to fetch data while page load. Load all the dates in View with ID.
  2. On page load, fire a javascript/jquery function.
  3. This function in turn fires an ajax call for each date with ID/data as parameter.
  4. Request received on server will in turn make cURL request to 3rd party server to get results.
  5. cURL request fetches required results and send it back to client.
  6. Client receives result as response to ajax call.
  7. Manipulate the response to show in View.
  8. Results will be displayed as and when response for respective date is received and manipulated, but it surely resolves PHP timeout error.

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