使用 PHP 将 Gmail 联系人导出为 CSV

发布于 2024-12-27 07:40:53 字数 1342 浏览 0 评论 0原文

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

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

这是文章: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() 的输出:

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

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

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.

Here is the article: http://www.ibm.com/developerworks/opensource/library/x-phpgooglecontact/index.html

And here is my code:

$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)

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) "[email protected]"
            }
        ["phoneNumber"] => array(2)
            {
                [0] => string(3) "123"
                [1]=> string(3) "321"
            }
     }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

七婞 2025-01-03 07:40:53

尝试此代码:

$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() 行:

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

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

但是...

上面的代码(基于您的代码)将生成一个难以解析的 CSV 文件。这是因为联系人可能有不同数量的电话号码和电子邮件地址。 CSV 文件应该是一个表格,具有明确定义的列,并且每行的列数相同。因此,您最好执行以下操作:

NB 此解决方案循环数据两次,以便动态构建列布局。这将是一个较慢的解决方案,可以通过严格定义列布局来加快速度,但这可能会导致列太多,一些列为空数据,或者列不足并且一些数据丢失。

$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);

Try this code:

$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);

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);

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...

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. 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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文