How to Export Contact as vCard using PHP

by Vincy. Last modified on July 3rd, 2023.

VCard or VCF is a virtual contact file containing contact information in a standard format. It is used to attach and transfer contact data via email or any other form of electronic data transfer. The vCard stores contact data like name, email, address, company, and more details. This tutorial will show how to export contact data to a vCard using PHP.

Previously, we have seen PHP contact form example to get the contact details from the user. In this example, the user contact and company details are stored in a database table.

View Demo

Data for contact is retrieved using PHP from the database and listed in a tabular format. In this list, each item will have the option to export data to a vCard format. Once exported, the vCard will be downloaded to the browser.

php-vcard-export-output

Previously, we have seen several examples to export database results to various format like CSV, and Excel. I have used Jeroen Desloovere’s vCard PHP library for exporting contact data to vCard. Download this library from Github and put it in your local environment to run this example.

Contact Data Table with vCard Export Option

This landing page displays the contact details from the database in a tabular form. In this PHP example, I have used MySQL prepared statement for performing database operations.

Initially, the query is executed to get all the contact details into a PHP array. This array of contacts is iterated and displayed in a tabular view with the vCard export option. By clicking this vCard Export control, the PHP export action will be called. Then the contact data will be exported to a VCF file and downloaded to the browser.

<?php
require_once "DBController.php";
$dbController = new DBController();

if(!empty($_GET["action"])) {
    $query = "SELECT * FROM tbl_contact WHERE id = ?";
    $param_type = "i";
    $param_value_array = array($_GET["id"]);
    $contactResult = $dbController->runQuery($query,$param_type,$param_value_array);
    
    require_once "VcardExport.php";
    $vcardExport = new VcardExport();
    $vcardExport->contactVcardExportService($contactResult);
    exit;
}

$query = "SELECT * FROM tbl_contact";
$result = $dbController->runBaseQuery($query);
?>
<!DOCTYPE html>
<html>
<head>
<title>How to Implement OTP SMS Mobile Verification in PHP with TextLocal</title>
<link href="style.css" type="text/css" rel="stylesheet" />
</head>
<body>
<?php 
if(!empty($result))
{
?>
    <div class="tbl-contact">
        <div class="contact-row-header">
            <div class="col_name">Name</div>
            <div>Email</div>
            <div>Phone</div>
            <div>Address</div>
            <div class="action">Export</div>
        </div>
<?php 
    foreach($result as $k=>$v)
    {
?>
        
        
        <div class="contact-row">
            <div class="col_name"><?php echo $result[$k]["first_name"]; ?> <?php echo $result[$k]["last_name"]; ?></div>
            <div><?php echo $result[$k]["email"]; ?></div>
            <div><?php echo $result[$k]["phone"]; ?></div>
            <div><?php echo $result[$k]["address"]; ?></div>
            <div class="action"><a href="index.php?action=export&id=<?php echo $result[$k]["id"]; ?>" title="Export to vCard"><img src="vcard_icon.png" alt="vCard"></a></div>
        </div>
<?php 
    }
?>
    </div>
<?php 
}
?>
</body>
</html>

PHP vCard Library Class Instantiation and Contact Data Export

In this PHP class, the required vCard library class is instantiated. Regarding this instance, the contact data is added to an object array. This contact data object will be passed while exporting data to the VCF file.

This vCard PHP library requires the Behat-Transliterator library for transliterating the name. So, download Behat-Transliterator library and use it as a dependency to run this example.

<?php
use JeroenDesloovere\VCard\VCard;

class VcardExport
{

    public function contactVcardExportService($contactResult)
    {
        require_once 'vendor/Behat-Transliterator/Transliterator.php';
        require_once 'vendor/jeroendesloovere-vcard/VCard.php';
        // define vcard
        $vcardObj = new VCard();

        // add personal data
        $vcardObj->addName($contactResult[0]["first_name"] . " " . $contactResult[0]["last_name"]);
        $vcardObj->addBirthday($contactResult[0]["date_of_birth"]);
        $vcardObj->addEmail($contactResult[0]["email"]);
        $vcardObj->addPhoneNumber($contactResult[0]["phone"]);
        $vcardObj->addAddress($contactResult[0]["address"]);
        
        return $vcardObj->download();
    }
}
?>

Database Controller

This PHP class was created as a database controller to handle connections and fetch data with PreparedStatement. The runBaseQuery() function receives and executes the query without parameters. The runQuery() function gets the query, param type, and values as its argument to bind with the query statement. This function is used to fetch contact data by id for exporting it to a VCF file.

<?php
class DBController {
	private $host = "localhost";
	private $user = "root";
	private $password = "test";
	private $database = "blog_samples";
	private $conn;
	
    function __construct() {
        $this->conn = $this->connectDB();
	}	
	
	function connectDB() {
		$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
		return $conn;
	}
	
    function runBaseQuery($query) {
        $result = $this->conn->query($query);	
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }
        return $resultset;
    }
    
    
    
    function runQuery($query, $param_type, $param_value_array) {
        $sql = $this->conn->prepare($query);
        $this->bindQueryParams($sql, $param_type, $param_value_array);
        $sql->execute();
        $result = $sql->get_result();
        
        if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                $resultset[] = $row;
            }
        }
        
        if(!empty($resultset)) {
            return $resultset;
        }
    }
    
    function bindQueryParams($sql, $param_type, $param_value_array) {
        $param_value_reference[] = & $param_type;
        for($i=0; $i<count($param_value_array); $i++) {
            $param_value_reference[] = & $param_value_array[$i];
        }
        call_user_func_array(array(
            $sql,
            'bind_param'
        ), $param_value_reference);
    }
}
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Comments to “How to Export Contact as vCard using PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page