使用PHP将Gmail联系人导出到CSV [英] Export Gmail Contacts to CSV using PHP

查看:124
本文介绍了使用PHP将Gmail联系人导出到CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个PHP脚本来备份我的Gmail联系人。

I'm trying to write a PHP script to backup my Gmail contacts.

我发现一篇文章描述了使用Zend框架与Google Contacts API为了查询联系人,我设法得到它的工作,但返回的信息量远远不够。

I found an article which described using the Zend framework in combination with the Google Contacts API in order to query contacts, I managed to get it working however the amount of information returned is far from adequate.

这是文章: http://www.ibm.com/developerworks/opensource/library/x-phpgooglecontact/index。 html

这里是我的代码:

$fp = fopen('file.csv', 'w');
foreach ($results as $r) {
  $master = array();
  $master[0] = (string) $r->name;
  $master[1] = (string) $r->orgName;
  $master[2] = (string) $r->orgTitle;
  $iCount = 2;
  foreach($r->phoneNumber as $p) {
    $iCount += 1;
    $master[$iCount] = (string) $p->phoneNumber;
  }
  fputcsv($fp, $master);
}
fclose($fp)

这里是var_dump ):

Here is the output from var_dump():

object(stdClass)#7 (5)
    {
        ["name"] => string(17) "John Doe"
        ["orgName"] => string(6) "Some Org"
        ["orgTitle"] => string(0) ""
        ["emailAddress"] => array(1)
            {
                [0]=> string(17) "user@domain.com"
            }
        ["phoneNumber"] => array(2)
            {
                [0] => string(3) "123"
                [1]=> string(3) "321"
            }
     }


推荐答案

请尝试以下代码:

$csvFile = 'file.csv';

// Open the CSV file for writing
if (!$fp = fopen($csvFile, 'w')) {
  exit("Unable to open '$csvFile' for writing");
}

// Loop results
foreach ($results as $r) {
  // Build base array
  $item = array($r->name, $r->orgName, $r->orgTitle);
  // Add phone numbers to array
  $item = array_merge($item, $r->phoneNumber);
  // Write to CSV file
  fputcsv($fp, $item);
}

fclose($fp);

此代码不会将电子邮件地址添加到文件,因为您尚未在代码中使用它们,但可以通过更改 array_merge() 这行:

This code does not add the email addresses to the file, because you have not used them in your code, but it could easily be added by changing the array_merge() line to this:

$item = array_merge($item, $r->phoneNumber, $r->emailAddress);

这将导致电子邮件地址显示在每行的末尾。要让它们出现在其他地方,你只需要改变提供参数到 array_merge()的顺序。

This would result in the email addresses appearing at the end of each row. To have them appear somewhere else, you just need to change the order in which you supply the arguments to array_merge().

HOWEVER ...

HOWEVER...

上述程式码会根据您的程式码产生CSV文件,将很难解析。这是因为联系人可以具有不同数量的电话号码和电子邮件地址。 CSV文件应该是一个表,其中包含明确定义的列,每行中的列数相同。因此,你最好做这样的事情:

The code above, based on your code, will result in a CSV file that will be difficult to parse. This is because the contact can have a varying number of phone numbers and emails addresses. A CSV file should be a table, with well defined columns and the same number of columns in each row. For this reason, you would be better doing something like this:

N.B。此解决方案循环数据两次,以便动态构建列布局。这将是一个较慢的解决方案,它可以通过严格定义列布局加快,但这可能会导致列太多,一些与空数据,或没有足够的列和一些数据丢失。 / p>

N.B. This solution loops the data twice in order to dynamically construct the column layout. This will be a slower solution and it could be speeded up by rigidly defining the column layout, but this will potentially result in either too many columns, some with empty data, or not enough columns and some data being lost.

$csvFile = 'file.csv';

// Loop the data to construct the maximum number of emails and telephone numbers
$numTels = $numEmails = 0;
foreach ($results as $r) {
  if (count($r->phoneNumber) > $numTels) $numTels = count($r->phoneNumber);
  if (count($r->emailAddress) > $numEmails) $numEmails = count($r->emailAddress);
}

// Open the CSV file for writing
if (!$fp = fopen($csvFile, 'w')) {
  exit("Unable to open '$csvFile' for writing");
}

// Construct the column headers row and write to file
$colHeaders = "name,orgname,orgtitle";
for ($i = 0; $i < $numTels; $i++) $colHeaders = ",tel_$i";
for ($i = 0; $i < $numEmails; $i++) $colHeaders = ",email_$i";
fwrite($fp, "$colHeaders\n");

// Construct and write rows to file
foreach ($results as $r) {
  $item = array($r->name, $r->orgName, $r->orgTitle);
  for ($i = 0; $i < $numTels; $i++) $item[] = (isset($r->phoneNumber[$i])) ? $r->phoneNumber[$i] : '';
  for ($i = 0; $i < $numEmails; $i++) $item[] = (isset($r->emailAddress[$i])) ? $r->emailAddress[$i] : '';
  fputcsv($fp, $item);
}

fclose($fp);

这篇关于使用PHP将Gmail联系人导出到CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆