Forum


Replies: 4   Views: 876
Bulkprocessing replace all variables in the same text tag
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 michael.stubenvoll  · 09-11-2021 - 16:47

I'm trying to use the replaceText function from BulkProcessing.php to replace a bunch of placeholders in a template docx file. This works fine unless there are multiple placeholders in a single <w:t> node in the WordprocessingML data of the docx file. Then only the first found placeholder will be replaced by its value while the other placeholders in the same node can't be replaced.

So for example if I have a docx file with a line such as (using Word 2019):

Hello $firstname$ $lastname$

The corresponding node in the WML data looks something like:

<w:t>Hello $firstname$ $lastname$</w:t>

And after a call to the replaceText method:

$bulk = new BulkProcessing($docx);
$bulk->replaceText([['firstname' => 'John', 'lastname' => 'Doe']])

the final document looks like:

Hello John $lastname$

 

Now if I insert the following lines into the variable2Text function in BulkProcessing.php it works just fine:

// PhpDocx 12 premium
// BulkProcessing.php, line 1025
protected function variable2Text($variables, $dom, $options)
    {
        // ...
        foreach ($variables as $variable => $value) {
            // ...
            foreach ($foundNodes as $node) {
                // ...
                $newNode = $dom->createDocumentFragment();
                @$newNode->appendXML($strNode);
                $dom->importNode($newNode, true);
                $node->parentNode->replaceChild($newNode, $node);

                /* My added code */
                $dom = $this->generateDomDocument($dom->saveXML());
                $xpath = new \DOMXPath($dom);
            }
        }
// ...

I wondered if there is a more elegant way of doing this, and if this is something that could be considered to be added to a future update. Else one might have to call the replaceText method once for each individual placeholder just to make sure it will be replaced. 

Thank you for your time and effort!