News

How to generate a dynamical table with a PHPDocX Word template

  • May 04, 2011

Very often we receive questions about how to generate dinamically a table with the help of a Word template.
One should first generate a docx document with a table that contains the required placeholder variables: The following PHP code does the required work:


require_once '../../classes/CreateDocx.inc';

$docx = new CreateDocx();

$settings = array(
'header' => true
);

// Here we call the template
$docx->addTemplate('../files/TemplateTable.docx');

// Now we define the values of the variables in the template
$docx->addTemplateVariable(
array(
array(
'NAME' => 'Product A',
'WEIGHT' => '10',
'PRICE' => '5',
),
array(
'NAME' => 'Product B',
'WEIGHT' => '20',
'PRICE' => '30',
),
array(
'NAME' => 'Product C',
'WEIGHT' => '25',
'PRICE' => '7',
),
),
'table',
$settings
);

$docx->addTemplateVariable('TOTALWEIGHT', '55');

$docx->addTemplateVariable('TOTALPRICE', '42');

$docx->addTemplateVariable('MYNAME', 'David Hume');

$docx->createDocx('template_table.docx');