Replies: 2   Views: 2653
Replacing a variable by wordfragment (pagenumber)
Topic closed:
Please note this is an old forum thread. Information in this post may be out-to-date and/or erroneous.
Every phpdocx version includes new features and improvements. Previously unsupported features may have been added to newer releases, or past issues may have been corrected.
We encourage you to download the current phpdocx version and check the Documentation available.

Posted by k.barendrecht  · 13-06-2017 - 12:14

I'm trying to replace a template variable with a pagenumber, but I'm getting a strange error (not what I would expect).


From the docs:

// create a Word fragment to insert in the default header
$numbering = new WordFragment($docx, 'defaultHeader');
// set some formatting options
$options = array('textAlign' => 'right',
'bold' => true,
'sz' => 14,
'color' => 'B70000',
$numbering->addPageNumber('numerical', $options);
$docx->addHeader(array('default' => $numbering));

My implementation: (where $this is an instance of CreateDocxFromTemplate)

  function addPageNumberingToDocument()
        // create a Word fragment
        $numbering = new WordFragment($this);
        $options = [
            'textAlign' => 'right',
            'bold' => false,
            'sz' => 14,
            'color' => '000000'
        $numbering->addPageNumber('numerical', $options);

        // Replace variables(pagenumber) in header and footer
        $this->replaceVariableByWordFragment(['pagenumber' => $numbering], ['target' => 'header']);
        $this->replaceVariableByWordFragment(['pagenumber' => $numbering], ['target' => 'footer']);


How should I go about replacing a variable with a pagenumber?

Posted by admin  · 13-06-2017 - 14:15


Sorry but we're unable to replicate the issue.

Please run this code standalone (using the classes from phpdocx without doing changes):


require_once 'classes/';

$docx = new CreateDocxFromTemplate('TemplateWordFragmentsTarget.docx');

$numbering = new WordFragment($docx);
$options = [
    'textAlign' => 'right',
    'bold' => false,
    'sz' => 14,
    'color' => '000000'
$numbering->addPageNumber('numerical', $options);

$docx->replaceVariableByWordFragment(['VAR_HEADER_3' => $numbering], ['target' => 'header']);
$docx->replaceVariableByWordFragment(['VAR_FOOTER_2' => $numbering], ['target' => 'footer']);


You may find the TemplateWordFragmentsTarget.docx in the examples/files folder. Do you get the same error?


PS we have changed your username to hide your email in the forum

Posted by k.barendrecht  · 11-07-2017 - 13:21

Not sure what went wrong. After changing the structure the error didnt occur anymore. I'm now calling the method from another class instead of my CreateDocx-wrapper and it works as intended.