I am trying to insert some data to the template however I keep getting a blank document with no data or template structure. It is just blank.
Here is the code:
$path = public_path('documents/mailing/');
$source = public_path('documents/default/main.docx');
$sales = Sale::where('status', '=', '1')
->where('special', '!=', 1)
->orderBy('updated_at', 'asc')
->get();
if( !File::exists($path) )
{
File::makeDirectory($path, 0775, true);
}
$phpWord = new \PhpOffice\PhpWord\PhpWord();
$template = $phpWord->loadTemplate($source);
foreach ($sales as $sale)
{
$template->addPage();
$template->setValue('saleRef', htmlspecialchars($sale->SaleID));
}
$objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$file = $path.'mailing_'.date("d-m-Y_H-i-s"). '.docx';
$objWriter->save($file);
I have also tried saving the template like so:
$file = $path.'mailing_'.date("d-m-Y_H-i-s"). '.docx';
$template->saveAs($file);
But when I do that I am getting a corrupted document in return with some XML errors which cannot be open in MS Word. What I am doing wrong?