Ankit
Ankit

Reputation: 65

How to get full contact information from Google using PHP?

I am using Oauth 2.0 to Import Contacts but I am getting only the email addresses. Any Way to Get Other Fields? Also, How can I create Contacts using Google API. Need to use Only PHP.

Here is my Code:

//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>";

Upvotes: 3

Views: 5513

Answers (2)

Ritin
Ritin

Reputation: 411

PHP GMAIL Contacts XML Parsing with DOMDocument and cURL

Dnt know about adding contacts but the above link should get you started in the right direction, create a DomDocument Class and append Nodes to it (php manual). I think would be the way to go, keeping inline with Google contact API's

Upvotes: 0

Jan Gerlinger
Jan Gerlinger

Reputation: 7415

Well, if you're only parsing the XML for gd:email then you certainly only get the email address. See the Contact kind documentation for an overview of the elements you could also parse for.

For creating contacts you can just issue a POST request with the contact details in the body to the same endpoint:

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

For detailed documentation on the format of the contact details, see the API documentation.

Upvotes: 3

Related Questions