Skip to content

Instantly share code, notes, and snippets.

@tdlm
Created February 2, 2021 07:55
Show Gist options
  • Save tdlm/629eca5adea2ba24a10d75d0d2e8e9e4 to your computer and use it in GitHub Desktop.
Save tdlm/629eca5adea2ba24a10d75d0d2e8e9e4 to your computer and use it in GitHub Desktop.
Convert a bunch of vCard (VCF files) to a CSV file output
{
"name": "scott/vcf-to-csv",
"require": {
"jeroendesloovere/vcard": "^1.7"
}
}
<?php
require_once __DIR__ . '/vendor/autoload.php';
use JeroenDesloovere\VCard\VCardParser;
$vcf_files = glob(__DIR__ . '/Contacts/*.vcf');
/**
* VCF get the first item of type from property array.
*
* @param array $array Property array.
* @param string $type Type string.
*
* @return string Item value.
*/
function vcf_get_item($array, $type) {
if (array_key_exists($type, $array) && count($array[$type])) {
return $array[$type][0];
}
return '';
}
/**
* Flatten VCF Data for CSV file.
*
* @param object $vcf_data VCF Data object.
*
* @return array Array hash of address data we care about.
*/
function flatten_vcf_data($vcf_data) {
return [
'Full Name' => $vcf_data->fullname,
'First Name' => $vcf_data->firstname,
'Last Name' => $vcf_data->lastname,
'Home Email' => property_exists($vcf_data, 'email') ? strtolower(vcf_get_item($vcf_data->email, 'home')) : '',
'Work Email' => property_exists($vcf_data, 'email') ? strtolower(vcf_get_item($vcf_data->email, 'work')) : '',
'Mobile Phone' => property_exists($vcf_data, 'phone') ? vcf_get_item($vcf_data->phone, 'mobile') : '',
];
}
$csv_lines = [
['Full Name', 'First Name', 'Last Name', 'Home Email', 'Work Email', 'Mobile Phone'],
];
foreach($vcf_files as $vcf_file) {
$parser = VCardParser::parseFromFile($vcf_file);
foreach($parser as $vcard) {
$csv_lines[] = flatten_vcf_data($vcard);
}
}
$fh = fopen('contacts.csv', 'wb');
foreach($csv_lines as $csv_line) {
fputcsv($fh, $csv_line);
}
fclose($fh);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment