2016-07-29 114 views
6

我想通過我的朋友的電子郵件獲得完整的聯繫人列表。 我可以得到聯繫人列表,但沒有電子郵件。Google 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>'; 

我怎樣才能從聯繫人列表的電子郵件嗎?

+0

有人幫助我嗎? –

+0

這裏是完全相同的問題與答案:http://stackoverflow.com/questions/21469433/how-to-get-email-address-when-user-is-authenticated-with-google-oauth2-and-peopl – Jehy

+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); 
0

您可以從GDATA組件使用聯繫人種類的谷歌聯繫人API的 假設$response是您向Google聯繫人索取的回覆:

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

查找谷歌API聯繫方式聯繫人種類元素的更多信息請參考here

相關問題