Forum


Replies: 1   Views: 19
Example docx with placeholders

Posted by robertwas  · 21-11-2024 - 22:07

I am currently trying to use the replaceVariableByHTML function of phpdocx,
this is the main reason I bought the product.

However, I cannot get the code working for me, so i think that I my approach is wrong.
I have seen the sample code here, but this doesn't give much info.

Is there an example document to see how the placeholders are made?
I would be served best if somebody would tell me how to make those placeholders in word.
What I am trying to do now is adding Rich text fields and replacing the placeholder by the name I gave those fields, but that doesnt seem to work.

Thanks for the advice / info

Posted by admin  · 22-11-2024 - 06:54

Hello,

We recommend you read the practical guide (https://www.phpdocx.com/documentation/practical) about templates:

To add placeholders in a DOCX template, you need to write the variables (placeholders) to be replaced, such as $VAR_NAME$ or using a custom template symbol ${VAR_ADDRESS} and call phpdocx template methods to replace them. Also please note that all packages include samples using all phpdocx methods in the examples folder.

The following steps illustrate a very simple sample using a DOCX template and replaceVariableByHTML:

  • Open MS Word, write some contents and a placeholder ($VAR$). Instead of the default template symbols to wrap placeholders ($), you can use setTemplateSymbol to set custom symbols ( for example ${ } ), to wrap placeholders.
  • Use the phpdocx template methods to replace the placeholder with the new contents:
$docx = new CreateDocxFromTemplate('template.docx');

$html = '<p style="font-family: verdana; font-size: 11px">phpdocx by <b>NarceaLabs</b></p>';
$docx->replaceVariableByHTML('VAR', 'block', $html);

$docx->createDocx('output');

Please note that placeholders to be replaced are added to the document as regular text content. If you use input fields, you may need to use modifyInputFields to replace them, but please note that input fields in MS Word are very limited.

If you send a DOCX template you are using, you can send it to contact[at]phpdocx.com and we'll check it to generate a custom sample script using it and make any changes to it if needed.

Regards.