使用oauth获取谷歌联系人姓名

时间:2012-06-28 08:01:39

标签: php oauth

目前,我正在使用一段代码从谷歌帐户获取谷歌联系人电子邮件并将其显示在表格中。电子邮件显示正确,但我希望该人的姓名也显示出来。我目前使用的代码如下。我知道$ xml包含名称(我尝试在html上打印)但我不知道如何显示它。 $ result不再包含名称所以我猜测显示的名称必须在此之前。有没有人有任何想法?

//passing accesstoken to obtain contact details
$xmlresponse =  file_get_contents('https://www.google.com/m8/feeds/contacts/default/full?oauth_token='.$tok_value.'&max-results=500');
//print_r($xmlresponse);
//reading xml using SimpleXML
$xml =  new SimpleXMLElement($xmlresponse);
//print_r($xml);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
//after dumping there is no names in the result
$result = $xml->xpath('//gd:email');
//var_dump($result);
$count = 0;
echo "<table class=\"inv-table\" cellpadding=\"5\">";
foreach ($result as $title) 
{
    //echo $title->attributes()->address . "<br><br>";
    echo "<tr><td><input type=\"checkbox\" 
                         name=\"email_to[]\" 
                         value=".$title->attributes()->address.">".$title->attributes()->address;
    echo "</td></tr>";
    //echo $title->attributes()->displayName;
    //echo $title->fullName;
    $count = $count + 1;
}
echo "</table>";

提前致谢!

4 个答案:

答案 0 :(得分:2)

将此代码放入循环中:

echo $xml->entry[$count]->title;

答案 1 :(得分:2)

我尝试了上面的方法,其中echo $xml->entry[$count]->title;不起作用,因为这没有为电子邮件提供正确的名称。相反,我这样做了:

// https://www.google.com/m8/feeds/contacts/default/full?updated-min=1970-03-16T00:00:00&max-results=10000");

function getNamesAndEmails ($xml_response) {
    $xml = new \SimpleXMLElement($xml_response);
    $xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');

    $results = array ();
    foreach($xml->entry as $entry){

        $xml = simplexml_load_string($entry->asXML());

        $ary = array ();
        $ary['name'] = (string) $entry->title;

        foreach ($xml->email as $e) {
          $ary['emailAddress'][] = (string) $e['address'];
        }

        if (isset($ary['emailAddress'][0])) {
            $ary['email'] = $ary['emailAddress'][0];
        }

        $results[] = $ary;

    }

    return $results;
}

答案 2 :(得分:1)

你能得到名字吗?我一直在努力解决同样的问题。

我注意到您尝试echo $title->fullName,它不会在$title下,因为这只是找到的所有电子邮件地址的结果,只有和地址​​以及其他一些可选项(这些都不是名字)。

如果你print_r($xml)你应该看到那里的名字,但对我来说,没有多少xpath可以为我找回它们。

答案 3 :(得分:0)

这是一个非常类似的解决方案但对我很有用:

$url = "https://www.google.com/m8/feeds/contacts/default/full?max-results=2000&oauth_token=$token";
$xmlresponse =  file_get_contents($url);
$xml =  new SimpleXMLElement($xmlresponse);
$xml->registerXPathNamespace('gd', 'http://schemas.google.com/g/2005');
$result = $xml->xpath('//gd:email');

$contacts = array();
foreach ($result as $key=>$title) {
    $contact = new stdClass();
    $contact->name = sprintf("%s", $xml->entry[$key]->title[0]);
    $contact->email = sprintf("%s", $title->attributes()->address);
    $contacts[] = $contact;
}

因此,循环之后,你有一个带有简单对象的数组,里面装满了名字和电子邮件。