'Codeigniter 4 with PHPWord loadTemplate

I have a problem loading a template doc in Codeigniter using PHPWord. The code below works but the downloaded word file is empty. I think the problem is that the location of the template is incorrect. Can anyone show/teach me how should I properly locate the template file. The template file file is located in public/template/ folder.

$phpWord  = new \PhpOffice\PhpWord\PhpWord();
$document = $phpWord->loadTemplate(./template/filedoc.docx);
$document->setValue('fullName',  'John Doe');
$document->setValue('date', date("F j Y"));
$xmlWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
$xmlWriter->save("php://output");
header("Content-Description: File Transfer");
header('Content-Disposition: attachment; filename="output.docx"');
header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Expires: 0');

Update: loadTemplate is now working fine no errors, the problem now is, why is it that the downloaded doc file is empty. Can anyone help?

$document = new \PhpOffice\PhpWord\TemplateProcessor(template/filedoc.docx)
$document->setValue('fullName',  'John Doe');
$document->setValue('date', date("F j Y"));
$document->saveAs('output.docx');

Change the code based on the current PHPWord documentaion for template processing. The output on the code above is still the same, empty document or rather unreadable by MSWord. Help...



Solution 1:[1]

constant APPPATH

The path to the app directory.

Instead of:

// ...
$document = $phpWord->loadTemplate(./template/filedoc.docx); ?
// ...

Use this:

// ...
$document = $phpWord->loadTemplate(APPPATH . "public/template/filedoc.docx"); ?
// ...

Solution 2:[2]

works for me



        $phpWord = new \PhpOffice\PhpWord\PhpWord();

        $section = $phpWord->addSection();

        $titleText = $section->addTextRun(array('alignment' => \PhpOffice\PhpWord\SimpleType\Jc::END));
   
        $titleText->addText('helooo ', array('size' => 12, 'rtl' => true));
        $section->addTextBreak(0.5);


 

        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
       
        $objWriter->save("demo.docx'");



its create file in public folder

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 steven7mwesigwa
Solution 2 paliz