我正在使用Google Contacts API,我能够提取姓名和电子邮件地址,但我也想获得个人资料照片和电话号码。
我使用PHP,这是我的代码,而认证:
//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
}
<<p> 电话号码/strong> 这部分获取电话号码不工作。
$phone = $xpath->query('//gd:phoneNumber');
foreach ( $phone as $row ){
print_r($row); // THIS PART DOESNT WORK
}
概要图
从上面的API链接来看,看起来我也可以从URL: https://www.google.com/m8/feeds/contacts/default/full
中抓取个人资料图片,但我不确定如何在我生成的DOMXPath
$xpath
对象中找到它。
想法吗?
Google Contacts API使用Atom提要。触点作为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文档的第一个示例响应,它返回:
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
属性用于将它们分类为home, work,…
获取图像:
图像作为具有特定rel
属性的Atom link
元素提供。
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)