PHPWord
PHPWord copied to clipboard
Add TemplateProcessor::getBlocks and TemplateProcessor::getBlock
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.
If this is a feature you'd like, I'm willing to provide a PR.
And furthermore being able to use these blocks to update contents would be great!
@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.
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;
}