采用php把电话号码生成vcf格式的通讯录文件
通讯录文件格式:
BEGIN:VCARD
VERSION:2.1
N:卫**#;;;;;
FN:卫**#
TEL;WORK;CELL:18123456789
END:VCARD
1.安装扩展
composer require jeroendesloovere/vcard
2.引用函数
/**
* 生成单个Vcf文件
* @return string
*/
public function createVcfFile(array $params): string
{
date_default_timezone_set('PRC');
$arData = $params;
$vcfdemo = new VCardIFL($arData);
$vcfdemo->createVcard();
return $vcfdemo->SaveVcard($this->fileDir) ? '创建成功!' : '创建失败!';
}
3.VCardIFL.php 函数方法:
<?php
namespace App\Common;
use JeroenDesloovere\VCard\VCard;
class VCardIFL
{
public $name;// 姓名
public $mobile;// 电话号码
public $fileName; // 文件名
public $saveTo;
private $vcard;
function __construct($arData)
{
if (is_array($arData) && !empty($arData)) {
$this->fileName = $arData["fileName"];
$this->saveTo = $arData["saveTo"];
$this->name= $arData["name"];
$this->mobile= $arData["mobile"];
}
}
function createVcard()
{
// Start Vcard Scritp
$this->vcard = "BEGIN:VCARD\r\n";
$this->vcard .= "VERSION:2.1\r\n";
if ($this->name!= "") {
$this->vcard .= "N:" . $this->name. ";;;;;" . "\r\n";
$this->vcard .= "FN:" . $this->name. "\r\n";
}
if ($this->mobile != "") {
$this->vcard .= "TEL;WORK;CELL:" . $this->mobile . "\r\n";
}
$this->vcard .= "END:VCARD\n";
}
public function SaveVcard($filePath)
{
$filePath = filePath . ".vcf";
// 检查文件是否存在
if (!file_exists($filePath)) {
// 文件不存在,创建文件
touch($filePath); // 创建空文件
// 或者使用以下代码写入内容
// file_put_contents($filePath, "Initial content for the file.");
}
// $handel = @fopen($this->saveTo . "/" . $this->fileName . ".vcf", "w");
$handel = @fopen($filePath, "w");
$write = @fwrite($handel, $this->vcard, strlen($this->vcard));
@fclose($handel);
return $write ? $filePath : '';
}
public function DownloadVcard()
{
header("Content-type: text/directory");
header("Content-Disposition: attachment; filename=" . $this->fileName . ".vcf" . "");
header('Content-Length:' . filesize($this->fileName . ".vcf"));
header("Pragma: public");
echo $this->vcard;
}
}
?>