PHP curl循环在第5次迭代后提前终止


PHP curl loop terminates early after 5th Iteration

这是我在使用curl之前遇到的一个问题。我们在每天开始时导入大量数据,其中一部分是对一些地址进行地理编码。我们使用google的API来做这个,所以一个简单的curl循环应该可以工作,至少我是这么认为的。

下面是我的两个函数:注意properties变量包含大约100个条目。然而,无论刷新多少次,循环总是在第5次迭代之后停止调用curl函数。注意,循环没有终止,只是丢失了对curl函数的调用。
function geocode()
    {
        $service_url = 'https://maps.googleapis.com/maps/api/geocode/json?key=' . GAPI_KEY . '&address=';
        $properties = $this->listing_model->get_non_geocoded();
        if ($properties) {
            foreach ($properties->result() as $property) {
                $service_url .= urlencode($property->address . "," . $property->city . "," . $property->state . " " . $property->zip);
                try {
                    $search = $this->curl($service_url);
                } catch (Exception $e) {
                    var_dump($e);
                }
            }
        }
    }
function curl($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        unset($ch);
        return $result;
    }

当然还有var dump:

...previous (first) 3 entries...
string '14' (length=2)
object(stdClass)[116]
  public 'lat' => float #######
  public 'lng' => float #######
string '15' (length=2)
object(stdClass)[131]
  public 'lat' => float  #######
  public 'lng' => float  #######
string '16' (length=2)
null <-- ? Should be from curl
string '17' (length=2)
null <-- ? Should be from curl
string '18' (length=2)
null <-- ? Should be from curl
string '19' (length=2)
null <-- ? Should be from curl

根据在这里找到的API文档:https://developers.google.com/maps/documentation/geocoding/,看起来您每秒只能执行5个调用,每天总共有2500个请求。

所以现在,我认为你的问题是如何正确处理速率限制,看起来这里有一些好主意:如何管理请求有限的API调用

(跟踪每个请求,在每组5个请求之间休眠,等等)

祝你好运!

编辑:对不起!没看出来你已经解决了。我想既然API的限制是5个,而你的循环每5次迭代就会失败,这是有关联的。