Sample code for 30+ languages & platforms
PHP Requires Chilkat v11.0.0+

Find a Gmail label ID by name

See more GMail REST API Examples

Look up a label using its exact display name, including any parent/child path. Labels and their IDs belong to the authenticated mailbox. Use Gmail’s returned ID when applying a user label to messages.

Authorize the application with https://www.googleapis.com/auth/gmail.labels. The example reads the access token from gmail-token.json in a private working directory. Authorize a desktop application.

Google documentation

Chilkat PHP Downloads

PHP
<?php

use Chilkat2\Http;
use Chilkat2\HttpResponse;
use Chilkat2\JsonObject;

$success = false;

// Assumes Chilkat is unlocked. See Global Unlock Sample.

$token = new JsonObject();
try {
    $token->LoadFile('gmail-token.json');
} catch (\Chilkat2\Exception $e) {
    echo "Could not read gmail-token.json from the private working directory.\n";
    exit;
}

if (($token->JsonTypeOf('access_token') != 1) || ($token->StringOfEquals('access_token', '', true))) {
    echo "An OAuth access token is required.\n";
    exit;
}

$http = new Http();
$http->RequireSslCertVerify = true;
$http->AuthToken = $token->StringOf('access_token');
$resp = new HttpResponse();
$reply = new JsonObject();
try {
    $http->HttpNoBody('GET', 'https://gmail.googleapis.com/gmail/v1/users/me/labels', $resp);
    $success = true;
} catch (\Chilkat2\Exception $e) {
    $success = false;
}
if ($resp->StatusCode == 0) {
    echo "Gmail did not return an HTTP response.\n";
    exit;
}

if ((!$success) || (($resp->StatusCode < 200) || ($resp->StatusCode >= 300))) {
    echo 'Gmail HTTP ', $resp->StatusCode, "\n";
    try {
        $reply->Load($resp->BodyStr);
        $success = true;
    } catch (\Chilkat2\Exception $e) {
        $success = false;
    }
    if ($success) {
        echo $reply->StringOf('error.message'), "\n";
    }

    exit;
}

try {
    $reply->Load($resp->BodyStr);
} catch (\Chilkat2\Exception $e) {
    echo "Expected a Gmail JSON response.\n";
    exit;
}

if ($reply->JsonTypeOf('labels') != 4) {
    echo "Expected a list of labels.\n";
    exit;
}

$label = new JsonObject();
try {
    $reply->FindRecord2('labels', 'name', 'To review', true, $label);
} catch (\Chilkat2\Exception $e) {
    echo "No label with that exact name. Check the name or create the label first.\n";
    exit;
}

echo 'Label ID: ', $label->StringOf('id'), "\n";