Google Calendar API使用PHP curl批量处理

时间:2014-11-20 12:33:30

标签: php curl google-calendar-api

任何人都可以指出我使用Google Calendar API批量输入事件的示例。

Google引用为https://developers.google.com/google-apps/calendar/batch,示例为:

POST /batch HTTP/1.1
Authorization: Bearer your_auth_token
Host: www.googleapis.com
Content-Type: multipart/mixed; boundary=batch_foobarbaz
Content-Length: total_content_length

--batch_foobarbaz
Content-Type: application/http
Content-ID: <item1:12930812@barnyard.example.com>

GET /farm/v1/animals/pony

--batch_foobarbaz
Content-Type: application/http
Content-ID: <item2:12930812@barnyard.example.com>

PUT /farm/v1/animals/sheep
Content-Type: application/json
Content-Length: part_content_length
If-Match: "etag/sheep"

{
  "animalName": "sheep",
  "animalAge": "5"
  "peltColor": "green",
}

--batch_foobarbaz
Content-Type: application/http
Content-ID: <item3:12930812@barnyard.example.com>

GET /farm/v1/animals
If-None-Match: "etag/animals"

--batch_foobarbaz--

我已经建立了一个效果很好的日记同步程序。它从我们的应用程序创建并填充日记。然而,填充需要很长时间,因此批量输入。

我想使用php和curl作为同步程序以这种方式编写。我以前使用过PHP库但不想使用它们。

1 个答案:

答案 0 :(得分:1)

这是我的2美分:

我查看了我在LOCAL postgres数据库中安排的事件列表以及我与Google日历同步的事件列表。我想检查一下我是否直接在Google日历上修改了它们(而不是我的数据库)。

基本上,在PHP中,我写道:

$batch = '';
$boundary = '--my_boundary';
$i = 0;
while ($event = pg_fetch_array($list_of_events)){
    $batch .= "\n" . $boundary . "\nContent-Type: application/http\nContent-ID: " . $event['meeting_id'] . "\n\nGET /calendar/v3/calendars/primary/events/" . $event['meeting_id'] . " \nIf-None-Match: \"" . $event['etag'] . "\"\n";
    $i ++ ;
    if ($i > 48){
        // we need to split the batch by packs of <50. Close this one and create the next one
        $batch .= "\n" . $boundary . "\n";
        $batches[] = $batch;
        $batch = '' ;
        $i=0;
    }
}
// close the current batch pack
if ($i > 0) $batches[] = $batch . "\n" . $boundary . "\n";

// send the packs. This can surely be optimized.
for ($i = 0 ; $i < count($batches) ; $i++) {
    $session = curl_init('https://www.googleapis.com/batch');
    curl_setopt($session, CURLOPT_POST, true);
    curl_setopt($session, CURLOPT_HTTPHEADER, array('Host: www.googleapis.com', 'Content-Type: multipart/mixed; boundary=' . $boundary, 'Authorization:  Bearer ' . $token, 'Content-Length: ' . strlen( $batches[$i])));
    curl_setopt ($session, CURLOPT_POSTFIELDS,  $batches[$i]);
    curl_setopt($session, CURLOPT_HEADER, true);
    curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($session, CURLOPT_VERBOSE, true);
    curl_setopt($session, CURLINFO_HEADER_OUT, true);
    curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);

    $resp = curl_exec($session);
    $api_response_info = curl_getinfo($session);
    $pack_of_answers = substr($resp, $api_response_info['header_size']);
    curl_close($session);

    // the pack of answers is in $pack_of_answers. You can split them thanks to a boundary, and deal with them at your convenience.
}