Forum


Replies: 8   Views: 3967
Replacevariablebytext very slow
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 bbreukelen  · 01-07-2016 - 15:42

I tried using the custom class for preprocessing my templates but it gave XML Dom errors and created corrupt files so I decided to just do a normal createFromTemplate, process it and then do a createDocx as I figures it probably saves the cleaned template.

Below is my code to handle caching. Note that in the folder where you keep the templates, a folder called "cache" must be created with write-access to the user running the process. Don't forget to remove the cached version of the template after making changes to the initial one. The cached files will be created at first run so the first run takes longer.

This saves quite a bit of time when replacing lots of variables.

class myProcessingClass {

   private function loadTemplate($File) { // tFile is the template file

        if (!is_readable($tFile)) { return null; }
        $tFilePath = pathinfo($tFile);
        $tFileCache = $tFilePath['dirname'] . '/cache/' . $tFilePath['filename'] . '.' . $tFilePath['extension'];
        if (! file_exists($tFileCache)) {
            $ret = $this->makeTemplateCache($tFile, $tFileCache);
            if (! $ret) { return null; }
        }

        try {
            return new CreateDocxFromTemplate($tFileCache, ['preprocessed' => true]);
        } catch (Exception $e) {
            return null;
        }
    }

    private function makeTemplateCache($tFile, $tFileCache) {
        try {
            $docx = new CreateDocxFromTemplate($tFile);
            $docx->processTemplate();
            $docx->createDocx(str_replace(".docx", "", $tFileCache));

            if (! file_exists($tFileCache)) { return false; }
            return true;

        } catch (Exception $e) {
            return false;
        }
    }

}