PHPWord icon indicating copy to clipboard operation
PHPWord copied to clipboard

Add TemplateProcessor::getBlocks and TemplateProcessor::getBlock

Open gisostallenberg opened this issue 4 years ago • 4 comments
trafficstars

To analyze a template I would like to get the all the blocks that are available (only names or array with name key and content value) and to be able to get a specific block's content.

Solution

$template = new \PhpOffice\PhpWord\TemplateProcessor('path/to/a.docx');
$template->getBlocks(); // gives ['block_name' => 'the block content', 'another_blockName' => 'the other content'] 
$template->getBlock('block_name'); // gives 'the block content'

Alternatives considered and tried

I tried if getVariables gives the blocks, but it does not. I looked into ways to extend the processor to be able to use internal methods to add the functionality myself, but the preg_matches that find the blocks by name are not in a scope that can be used and to find all the blocks another regex is needed.

gisostallenberg avatar Jun 25 '21 07:06 gisostallenberg

If this is a feature you'd like, I'm willing to provide a PR.

gisostallenberg avatar Jun 25 '21 07:06 gisostallenberg

And furthermore being able to use these blocks to update contents would be great!

nesben avatar Jul 02 '21 08:07 nesben

@Aeka123 this is already possible AFAIK, see https://github.com/PHPOffice/PHPWord/issues/1390. Or do you mean something else? But at the moment you must know the block names from the templates, which makes it impossible to do something with them programmatically for any template offered.

gisostallenberg avatar Jul 07 '21 13:07 gisostallenberg

public function getBlocks()
{
    $variables = array_keys($this->getVariableCount());
    $first = true;
    $previous = '';

    foreach ($variables as $variable) {
        if ($first) {
            $previous = $variable;
            $first = false;
        } else {
            if (strpos($variable, $previous)) {
                $separated = explode("/", $variable);
                if ($separated[1] == $previous) {
                    $blocks[] = $previous;
                }
            }
            $previous = $variable;
        }
    }

    return $blocks;
}

enegyluvagyok avatar Aug 10 '22 10:08 enegyluvagyok