使用curl獲取google聯絡人列表 (向zend的Gdata say no)

modun1986發表於2010-02-09

登陸google

 

public function googleLogin($email,$password){
  		$session = UserOper::openSession();//如果已經登陸,直接返回
  		if($session['googleAuth']){
  			$session->close();
  			return true;
  		}
  		$data = array(  
		    'accountType' => 'GOOGLE',  
		    'Email' => $email,  
		    'Passwd' => $password,  
		    'service' => 'cp',  //google 一系列api 的簡寫,在google 上能找到,可以換成你想要的服務簡寫
		    'source' => 'test-oauth-1.0',  //給你自己的應用程式命名
		);  
		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_URL, "https://www.google.com/accounts/ClientLogin");  
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
		curl_setopt($ch, CURLOPT_POST, true);  
		curl_setopt($ch, CURLOPT_POSTFIELDS, $data);  
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
		$output = curl_exec($ch);
		$info = curl_getinfo($ch); 
		preg_match('/Auth=.+/',$output,$tempArray);
		if($info['http_code']!=200 or empty($tempArray)){
			return false;
		}
		$auth = 'Authorization: GoogleLogin auth='.substr($tempArray[0],5); 
		$session['googleAuth'] = $auth;
		return true;
  	}

 獲取聯絡人資訊(atom格式資料來源)

 

public function getGoogleResource($url){
  		$session = UserOper::openSession();
  		if(!$session['googleAuth']){
  			$session->close();
  			return false;
  		}
  		$session->close();
  		$ch = curl_init();  
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER,array($session['googleAuth']));  
		$output = curl_exec($ch);
		$info = curl_getinfo($ch);
		if($info['http_code']!=200) return false;
		return $output;
  	}

 解析資料來源,讀取聯絡人email地址(使用 php DOMDocument)

 

public function getGoogleFriends(){
  		$url = 'http://www.google.com/m8/feeds/contacts/default/full';
  		$source = $this->getGoogleResource($url);
  		$friends = array();
  		if($source){
  			$dom = new DOMDocument();
  			$dom->loadXML($source);
  			$entries = $dom->getElementsByTagName('entry');
  			foreach ( $entries as $entry ){
  				$email = $entry->getElementsByTagName('email');
  				$value = $email->item(0)->getAttributeNode("address")->value;
  				$friends[$value] = $value;
  			}
  			return $friends;
  		}
  		return false;
  	}

相關文章