7

我正在向服务器发送 curl 请求,该服务器需要几秒钟来处理请求并发出响应。我相信我的 php 脚本正在继续运行而不是等待,因此我基于响应的 foreach 循环吐出 0 个结果。在继续处理数据之前,如何等待 curl 事务完成?

  $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
  }
4

2 回答 2

21

curl 被阻塞,这意味着:

$result = json_decode($ret,true);

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

直到:

$ret = curl_exec($curl);

已经完成。您可以使用 curl_error() 并使用 curl_getinfo() 检查 HTTP 响应代码来检查错误和其他问题。

于 2013-11-06T16:37:53.763 回答
1

这真的很奇怪!,它不应该像你得到的那样发生。但无论如何尝试这样..

获取httpresponse代码,然后检查...

$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);
  $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  if($httpcode==200)
  {
  $result = json_decode($ret,true);
  foreach ($result['data'] as $key => $value)
  {
        //process data from $result
  }
  }
于 2013-11-06T16:34:40.127 回答