PHPWord icon indicating copy to clipboard operation
PHPWord copied to clipboard

A function returning all variables in docx template

Open nmauludina opened this issue 2 years ago • 1 comments

Is your feature request related to a problem? Please describe.

I want to make dynamic form input base on all the variables exist in docx template.

Describe the solution you'd like

I think it's better if there is a function that can return all variables inside the docx

Additional context

If it feature already exist feel free to tell me

nmauludina avatar Mar 09 '23 07:03 nmauludina

For all variables -> getVariables():

https://github.com/PHPOffice/PHPWord/blob/77438025265482ddcf050bce520d3c2b51645108/src/PhpWord/TemplateProcessor.php#L704-L712

If you want without blocks:

public function getVariablesWithoutBlock(): array
{
    $variables    = $templateProcessor->getVariables();
    
    $keysToRemove = [];
    $key_endBlock = null;
    foreach ($variables as $index => $variable) {
        if ($key_endBlock && $index <= $key_endBlock) {
            $keysToRemove[$index] = $index;
            continue;
        }

        $key_endBlock = array_search("/$variable", $variables, true)
        if ($key_endBlock) {
            // Is a block
            $keysToRemove[$index] = $index;
        }
    }

    return array_values(array_diff_key($variables, $keysToRemove));
}

cavasinf avatar Jun 27 '23 13:06 cavasinf