Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am sending a curl request to a server that needs a few seconds to process the request and spit out a response. I believe my php script is continuing on and not waiting, therefore my foreach loop based on the response is spitting out 0 results. How can i wait for the curl transaction to complete before moving on and processing data?

  $curl = curl_init();
  curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  curl_setopt($curl, CURLOPT_USERPWD, "admin:password");
  curl_setopt($curl, CURLOPT_URL, "http://server/r/?dst_user__substr='user'");


  curl_setopt($curl, CURLOPT_VERBOSE, 1);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $ret = curl_exec($curl);
  $result = json_decode($ret,true);

 <<<<I need to wait until transaction is complete here>>>>

  foreach ($result['data'] as $key => $value)
  {
        //process data from $result
  }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.3k views
Welcome To Ask or Share your Answers For Others

1 Answer

curl is blocking, which means that:

$result = json_decode($ret,true);

foreach ($result['data'] as $key => $value)
{
      //process data from $result
}

won't execute until:

$ret = curl_exec($curl);

is complete. You can check for errors and other issues using curl_error() and by checking the HTTP response code with curl_getinfo().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...