如何使用PHP从Google获取完整的联系信息?

时间:2012-08-12 07:40:26

标签: php api oauth

我使用Oauth 2.0导入联系人,但我只收到电子邮件地址。获得其他领域的任何方式?另外,如何使用Google API创建联系人。 需要只使用PHP。

这是我的代码:

//setting parameters
$authcode= $_GET["code"];
$clientid='xxxxxxx';
$clientsecret='secret';
$redirecturi='validate.php';
$fields=array(
 'code'=>  urlencode($authcode),
 'client_id'=>  urlencode($clientid),
 'client_secret'=>  urlencode($clientsecret),
 'redirect_uri'=>  urlencode($redirecturi),
 'grant_type'=>  urlencode('authorization_code')
);
//url-ify the data for the POST
$fields_string='';
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
$fields_string=rtrim($fields_string,'&');
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,'https://accounts.google.com/o/oauth2/token');
curl_setopt($ch,CURLOPT_POST,5);
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
// Set so curl_exec returns the result instead of outputting it.
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//to trust any ssl certificates
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//execute post
$result = curl_exec($ch);
//close connection
curl_close($ch);
//extracting access_token from response string
$response=  json_decode($result);
$accesstoken= $response->access_token;
//passing accesstoken to obtain contact details
$xmlresponse=  file_get_contents('https://www.google.com/m8/feeds/contacts/default     /full?oauth_token='.$accesstoken.'&max-results=5');
//reading xml using SimpleXML
 $xml=  new SimpleXMLElement($xmlresponse);
 $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
 $result = $xml->xpath('//gd:email');
 foreach ($result as $title) {
  $addrss=$title->attributes()->address;
  echo $addrss."<br><br>";

2 个答案:

答案 0 :(得分:3)

好吧,如果您只是为gd:email解析XML,那么您当然只能获得电子邮件地址。有关您也可以解析的元素的概述,请参阅Contact kind documentation

要创建联系人,您只需发出POST请求,并将正文中的联系人详细信息发送到同一端点:

https://www.google.com/m8/feeds/contacts/default/full

有关联系方式格式的详细说明,请参阅API documentation

答案 1 :(得分:0)

PHP GMAIL Contacts XML Parsing with DOMDocument and cURL

Dnt知道添加联系人,但上面的链接应该让你开始正确的方向,创建一个DomDocument类并将节点附加到它(PHP手册)。我认为应该采用这种方式,与Google联系API的内容保持一致