Google通讯录API获取电话号码(PHP)

时间:2015-07-14 12:03:16

标签: php xml google-api google-api-php-client google-contacts

我正在使用Google Contacts API,我可以提取姓名和电子邮件地址,但我也想获取个人资料照片和电话号码。

我使用PHP并在验证时使用了我的代码:

$widthCell = .content.width

电话号码

此部分的电话号码不会工作。

//if authenticated successfully...

$req = new Google_HttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);

$doc = new DOMDocument;
$doc->recover = true;
$doc->loadXML($val->getResponseBody());

$xpath = new DOMXPath($doc);
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');

$emails = $xpath->query('//gd:email');

foreach ( $emails as $email ){

  echo $email->getAttribute('address'); //successfully gets person's email address

  echo $email->parentNode->getElementsByTagName('title')->item(0)->textContent; //successfully gets person's name

}

个人资料图片

从上面的API链接判断,看起来我也可以从网址抓取个人资料图片:$phone = $xpath->query('//gd:phoneNumber'); foreach ( $phone as $row ){ print_r($row); // THIS PART DOESNT WORK } 但我不确定如何在https://www.google.com/m8/feeds/contacts/default/full {{中找到它我生成的对象。

思想?

1 个答案:

答案 0 :(得分:2)

Google Contacts API使用Atom Feed。联系人以entry个元素提供。因此迭代它们更有意义。要做到这一点,你还必须为atom命名空间注册一个前缀。

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
$xpath->registerNamespace('gd', 'http://schemas.google.com/g/2005');

如果使用DOMXpath :: evaluate(),则可以使用返回标量的表达式。第二个参数是表达式的上下文节点。

foreach ($xpath->evaluate('/atom:feed/atom:entry') as $entry) {
  $contact = [
    'name' => $xpath->evaluate('string(atom:title)', $entry),
    'image' => $xpath->evaluate('string(atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href)', $entry),
    'emails' => [],
    'numbers' => []
  ];
  foreach ($xpath->evaluate('gd:email', $entry) as $email) {
    $contact['emails'][] = $email->getAttribute('address');
  }
  foreach ($xpath->evaluate('gd:phoneNumber', $entry) as $number) {
    $contact['numbers'][] = trim($number->textContent);
  }
  var_dump($contact);
}

来自Google Contacts API documentation的第一个示例响应返回:

array(3) {
  ["name"]=>
  string(17) "Fitzwilliam Darcy"
  ["image"]=>
  string(64) "https://www.google.com/m8/feeds/photos/media/userEmail/contactId"
  ["email"]=>
  string(0) ""
  ["numbers"]=>
  array(1) {
    [0]=>
    string(3) "456"
  }
}

该示例不包含email元素,因此它为空。联系人可以拥有多个电子邮件地址和/或电话号码,或者根本没有。提供rel属性是为了将它们归类为家庭,工作......

获取图像:

图片是以具有特定link属性的Atom rel元素提供的。

atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]

这将返回link节点,但可以直接获取href属性:

atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href

将属性节点列表转换为字符串:

string(atom:link[@rel="http://schemas.google.com/contacts/2008/rel#photo"]/@href)