Google API - 获取联系人邮件

时间:2016-07-29 09:53:35

标签: php json api

我想通过朋友的电子邮件获取完整的联系人列表。 我可以获取联系人列表但没有电子邮件。

此处是我的代码:

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>';

如何从联系人列表中收到电子邮件?

2 个答案:

答案 0 :(得分:3)

我有解决方案:

代码:

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

更改为:

$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);

答案 1 :(得分:0)

您可以使用Google Contact API中gdata组件的联系种类 假设$response是您从Google联系人处获得的回复:

 $xml=  new SimpleXMLElement($response);
 $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
 $result = $xml->xpath('//gd:email');

在Google Contact API上查找有关Contact Kind元素的更多信息,请参阅here