I was wondering what is the best way to create vCard. I don't need to store it on my server, just generate it when user wants to download it. The below code works, but it seems clumsy to me, is there any better way?
<?php
function raf_create_vcard(){
$format_name = utf8_encode($name);
$format_email = utf8_encode($email);
$format_tel = utf8_encode($tel);
$format_fax = utf8_encode($fax);
$format_www = utf8_encode($www);
$format_address = utf8_encode($address);
return 'BEGIN%3AVCARD%0D%0AVERSION%3A4.0%0D%0AN%3A%3B'.$format_name.'%3B%3B%3B%0D%0AFN%3A'.$format_name.'%0D%0AEMAIL%3A'.$format_email.'%0D%0AORG%3A'.$format_name.'%0D%0ATEL%3A'.$format_tel.'%0D%0ATEL%3Btype%3DFAX%3A'.$format_fax.'%0D%0AURL%3Btype%3Dpref%3A'.$format_www.'%0D%0AADR%3A%3B'.$format_address.'%3B%3B%3B%3B%3BSpain%0D%0AEND%3AVCARD';
}
?>
Generating link:
<a href="data:text/plain;charset=UTF-8,<?php echo raf_create_vcard(); ?>" download="contact.vcf">Download</a>
Add url link in <a> tag for generate Vcard like
<a href="vcard.php?id=1">Generate VCard</a>
You write a code directly in php file save below code in vcard.php file
<?php
require_once('config.php');
$sql="SELECT * FROM USER WHERE id=".$_GET['id'];
$result=mysql_fetch_row(mysql_query($sql));
// define here all the variable like $name,$image,$company_name & all other
header('Content-Type: text/x-vcard');
header('Content-Disposition: inline; filename= "'.$name.'.vcf"');
if($image!=""){
$getPhoto = file_get_contents($image);
$b64vcard = base64_encode($getPhoto);
$b64mline = chunk_split($b64vcard,74,"\n");
$b64final = preg_replace('/(.+)/', ' $1', $b64mline);
$photo = $b64final;
}
$vCard = "BEGIN:VCARD\r\n";
$vCard .= "VERSION:3.0\r\n";
$vCard .= "FN:" . $name . "\r\n";
$vCard .= "TITLE:" . $company_name . "\r\n";
if($email){
$vCard .= "EMAIL;TYPE=internet,pref:" . $email . "\r\n";
}
if($getPhoto){
$vCard .= "PHOTO;ENCODING=b;TYPE=JPEG:";
$vCard .= $photo . "\r\n";
}
if($mobile_no){
$vCard .= "TEL;TYPE=work,voice:" . $mobile_no . "\r\n";
}
$vCard .= "END:VCARD\r\n";
echo $vCard;
?>
Without a library you could write it like that:
function raf_create_vcard(){
return utf8_encode('BEGIN:VCARD
VERSION:4.0
N:;'.$name.';;;
FN:'.$name.'
EMAIL:'.$email.'
ORG:'.$name.'
TEL:'.$tel.'
TEL;type=FAX:'.$fax.'
URL;type=PREF:'.$www.'
ADR:;'.$address.';;;;;Spain
END:VCARD');
}
But you should use a PHP library for that purpose. Check this out: https://github.com/jeroendesloovere/vcard.
use JeroenDesloovere\VCard\VCard;
$vcard = new VCard();
$vcard->addName($name);
$vcard->addCompany($name);
$vcard->addEmail($email);
$vcard->addPhoneNumber($tel);
$vcard->addPhoneNumber($fax, 'FAX');
$vcard->addURL($www, 'PREF');
$vcard->addAddress($address, null, null, null, null, null, 'Spain');
$vcardAsString = $vcard->getOutput();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With