1. Instalasi PHPWord
Jika menggunakan Composer, jalankan perintah berikut di terminal:
composer require phpoffice/phpword
2. Membuat Template DOCX
Buat dokumen template.docx menggunakan Microsoft Word, lalu tambahkan placeholder seperti:
- {nama}
- {nip}
- {jabatan}
- {alamat}
Simpan file ini dalam folder proyek, misalnya templates/template.docx.
3. Script PHP untuk Mengisi Template
Buat file generate_docx.php dengan kode berikut:
<?php
require 'vendor/autoload.php'; // Jika menggunakan Composer
use PhpOffice\PhpWord\TemplateProcessor;
// Data array
$data = [
'nama' => 'Budi Santoso',
'nip' => '123456789',
'jabatan' => 'Analis Kepegawaian',
'alamat' => 'Jl. Merdeka No. 45, Trenggalek'
];
// Load template DOCX
$templatePath = 'templates/template.docx';
$templateProcessor = new TemplateProcessor($templatePath);
// Ganti placeholder dengan data
foreach ($data as $key => $value) {
$templateProcessor->setValue($key, $value);
}
// Simpan hasil sebagai file baru
$outputFile = 'output_surat.docx';
$templateProcessor->saveAs($outputFile);
// Berikan respons ke browser untuk diunduh
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=" . basename($outputFile));
header("Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document");
header("Content-Length: " . filesize($outputFile));
readfile($outputFile);
// Hapus file setelah diunduh (opsional)
unlink($outputFile);
exit;
Mungkin langkah selanjutnya:
- konek ke database
- mendownload semua SK massal ke zip
Top comments (0)