Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google API - get contacts mail

Tags:

json

php

api

I want to get full contact lists with emails of my friends. I can get the list of contacts but not having emails.

Here is my code:

require_once APPPATH . 'vendor/google/src/Google_Client.php';
require_once APPPATH . 'vendor/google/src/contrib/Google_Oauth2Service.php';
$client = new Google_Client();

$client->setApplicationName("PHP Google Test");
$client->setClientId('xxx');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://www.domain.xx/admin/others/google?test');
$client->setScopes("http://www.google.com/m8/feeds/");

$oauth2 = new Google_Oauth2Service($client);

if (isset($_GET['code'])) {
    $client->authenticate();
    $_SESSION['token'] = $client->getAccessToken();
    $redirect          = 'http://www.domain.xx/admin/others/google';
    header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
}
if (isset($_SESSION['token'])) {
    $client->setAccessToken($_SESSION['token']);
}
if (isset($_REQUEST['logout'])) {
    unset($_SESSION['token']);
    $client->revokeToken();
}
if ($client->getAccessToken()) {
    $req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
    $val = $client->getIo()->authenticatedRequest($req);
    $response = json_encode(simplexml_load_string($val->getResponseBody()));
    print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";
    $_SESSION['token'] = $client->getAccessToken();
} else {
    $auth = $client->createAuthUrl();
}

$auth = $client->createAuthUrl();

echo '<a href="' . $auth . '" target="_blank">' . $auth . '</a>';

How can i get email from contacts list?

like image 732
Arkadiusz G. Avatar asked Jul 29 '16 09:07

Arkadiusz G.


1 Answers

I have solution:

Code:

$response = json_encode(simplexml_load_string($val->getResponseBody()));
print "<pre>" . print_r(json_decode($response, true), true) . "</pre>";

Change to:

$xml = simplexml_load_string($val->getResponseBody());
            $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');         

            $output_array = array();
            foreach ($xml->entry as $entry) {
              foreach ($entry->xpath('gd:email') as $email) {
                $output_array[] = array((string)$entry->title, (string)$email->attributes()->address);
              }
            }
           print_r($output_array);
like image 115
Arkadiusz G. Avatar answered Sep 27 '22 17:09

Arkadiusz G.