简体   繁体   English

带Curl请求的For循环-PHP

[英]For loop with Curl request - PHP

I'm checking against a list of address books (outputted as checkboxes) to see which books the user has selected. 我正在检查通讯录列表(以复选框形式输出),以查看用户选择了哪些通讯录。 For the selected ones I'm adding them to an ESP via their API using curl. 对于选定的对象,我将使用curl通过它们的API将它们添加到ESP中。

I have the following code which is achieving the desired result, however it's causing a pretty slow page load, I think this is because I'm looping through a large chunk of curl requests up to 15 times (once for each address book) and wondered if someone could help me tidy this up? 我有以下代码可以达到期望的结果,但是这会导致页面加载非常缓慢,我认为这是因为我正在遍历多达15次(每个地址簿一次)的大量curl请求,并且想知道是否有人可以帮我整理一下?

$aBook = $_POST['addressBooks'];
$N = count($aBook);

    for($i=0; $i < $N; $i++)
    {
      $content = [
            'email' => $_POST['email']
        ];
        global $baseUrl, $apiUsername, $apiPassword;
        $url = $baseUrl . '/v2/address-books/' . $aBook[$i] . '/contacts';
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt(
            $ch, CURLOPT_HTTPHEADER, array('Accept: application/json',
                                           'Content-Type: application/json')
        );
        curl_setopt($ch, CURLAUTH_BASIC, CURLAUTH_DIGEST);
        curl_setopt(
            $ch, CURLOPT_USERPWD,
            $apiUsername . ':' . $apiPassword
        );
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS,json_encode($content));

        $response = json_decode(curl_exec($ch));

    }

Since $abook is an array, why not serialize it and send just one curl request and do your backend processing once. 由于$ abook是一个数组,为什么不序列化它并仅发送一个curl请求,并进行一次后端处理。 If firing multiple queries using transactions would be good. 如果使用事务触发多个查询会很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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