export docx template with phpword

hi, i’m using phpword to export a docx template with some parameters, but i can’t get it to work, this is my code:

function Row_Export($rs)
{

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('cliente.docx');
    
	$cliente = $rs["cliente"];

  
   
      $templateProcessor->setValue('cliente', $cliente);
 
    $templateProcessor->saveAs('php://output');
    
}
  1. You still need Page_Exporting server event,
  2. Row_Export is fired for every row, you should not output file there, or only one row is exported, so your code only works (if it works) for the View page.
  3. Make sure you provide the correct path of the template, if you just use ‘cliente.docx’, that means the ‘cliente.docx’ is placed in the same folder as the script.
  4. Always enable Debug during development and check PHP errors in the log file.

I practically managed to generate the docx file but I only managed to save it on my server it doesn’t download me directly from the browserthis is my code:

function Page_Exporting()
{
    //$this->ExportDoc->Text = "my header"; // Export header
    //return false; // Return false to skip default export and use Row_Export event
    return false; // Return true to use default export and skip Row_Export event
}

function Row_Export($rs)
{
    
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templates/cliente.docx');
    $cliente = $rs["cliente"];
     $templateProcessor->setValue('cliente', $cliente);
     $templateProcessor->saveAs('php://output');

}

The save() method returns the file path, then you may use PHP’s readfile().

if I insert readfile () it gives me this error
Call to undefined method PhpOffice \ PhpWord \ TemplateProcessor :: readfile ()my code:

function Row_Export($rs)
{
    
    $templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('templates/cliente.docx');
    $cliente = $rs["cliente"];
     $templateProcessor->setValue('cliente', $cliente);

     
     $file = 'monkey.docx';


    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="'.basename($file).'"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    
     $templateProcessor->readfile($file);

}

You may read and learn Using namespaces: Basics → Example #1.

Hi, I don’t understand which classes conflict

arbei wrote:

You may read and learn > Using namespaces: Basics > → > Example #1> :

Example #1 Accessing global classes, functions and constants from within a namespace