Export Gmail Contacts to CSV using PHP

雨燕双飞 提交于 2019-12-11 08:18:44

问题


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) "user@domain.com"
            }
        ["phoneNumber"] => array(2)
            {
                [0] => string(3) "123"
                [1]=> string(3) "321"
            }
     }

回答1:


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


来源:https://stackoverflow.com/questions/8892612/export-gmail-contacts-to-csv-using-php

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!