Skip to content

Added support for word "mail merge" fields #487

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions docs/templates-processing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,27 @@ multirow from a single row in a template by using ``TemplateProcessor::cloneRow`
See ``Sample_23_TemplateBlock.php`` for example on how to clone a block
of text using ``TemplateProcessor::cloneBlock`` and delete a block of text using
``TemplateProcessor::deleteBlock``.



Merge field processing
======================

NOTE: This method has been successfully tested on a limited number of Word template documents. However, due to the complex nature of the underlying XML format, it may not work in all circumstances.

This method was designed to find and replace text using the standard Word "mail merge fields" in a document (including body, headers, and footers). When viewing a document in Word, these typically appear encapsulated as «FIELD_NAME».

Values for all merge fields within a document are passed as an array. The methods 'getMergeSuccess' and 'getMergeFailure' each return an array showing the status of the merge replacements throughout the document sections.

Example:

.. code-block:: php

$templateProcessor = new \PhpOffice\PhpWord\TemplateProcessor('Template.docx');
$templateProcessor->setMergeData(array(
'FIELD_NAME' => 'My Name',
'OTHER_VALUE' => $value
));
$templateProcessor->doMerge();
print_r( $templateProcessor->getMergeSuccess() );
print_r( $templateProcessor->getMergeFailure() );
88 changes: 88 additions & 0 deletions src/PhpWord/TemplateProcessor.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,15 @@ class TemplateProcessor
* @var string[]
*/
private $temporaryDocumentFooters = array();

/**
* Merge field replacement reporting information
*/
private $temporarySectionName;
private $mergeData = array();
private $mergeSuccess = array();
private $mergeFailure = array();


/**
* @since 0.12.0 Throws CreateTemporaryFileException and CopyFileException instead of Exception.
Expand Down Expand Up @@ -145,7 +154,86 @@ public function setValue($search, $replace, $limit = -1)
}
}


/**
* @return void
--> searches for office-defined merge fields, using $mergeData
*/
public function setMergeData($data) {
$this->mergeData = $data;
}

public function getMergeSuccess() {
return $this->mergeSuccess;
}
public function getMergeFailure() {
return $this->mergeFailure;
}

public function doMerge()
{
$this->mergeData = array_change_key_case($this->mergeData, CASE_UPPER);

foreach ($this->temporaryDocumentHeaders as $index => $headerXML) {
$this->temporarySectionName = 'header'.$index;
$this->temporaryDocumentHeaders[$index] = $this->doMergeForPart($this->temporaryDocumentHeaders[$index]);
}

$this->temporarySectionName = 'document';
$this->temporaryDocumentMainPart = $this->doMergeForPart($this->temporaryDocumentMainPart);

foreach ($this->temporaryDocumentFooters as $index => $headerXML) {
$this->temporarySectionName = 'footer'.$index;
$this->temporaryDocumentFooters[$index] = $this->doMergeForPart($this->temporaryDocumentFooters[$index]);
}
}

/**
* Find and replace merge fields in the given XML section.
* @return string
*/
protected function doMergeForPart($documentPartXML)
{
// break down major sections <w:p>
return preg_replace_callback("/<w:p[\s>].+?<\/w:p>/si", array($this, 'parseMergeSection'), $documentPartXML);
}

protected function parseMergeSection($replace)
{
$section = $replace[0];
$section = preg_replace('/<\/w:instrText><\/w:r><w:r\s+w:rsidR="\w+"><w:instrText\s+xml:space="preserve">/si', '', $section);
return preg_replace_callback("/(<w:r[\s>]((?!<\/w:r>).)*?<w:fldChar\s+w:fldCharType=\"begin\"\/>.*?<\/w:r>)\s*(<w:r[\s>].+?\s+MERGEFIELD\s+\"*\w+\"*\s+.+?<\/w:r>)\s*(<w:r[\s>].*?<w:fldChar\s+w:fldCharType=\"separate\"\/>.*?<\/w:r>)\s*(<w:r[\s>].+?<\/w:r>)\s*(<w:r[\s>].*?<w:fldChar\s+w:fldCharType=\"end\"\/>.*?<\/w:r>)/si", array($this, 'parseMergeReplace'), $section);
}

protected function parseMergeReplace($replace)
{
/* $replace: array 1..x corresponds to () matches in preg_replace */
$field = $replace[3];
$final = $replace[5];

if (preg_match('/(<w:instrText.+?\s+MERGEFIELD\s+\"*)(\w+)(\"*\s+<\/w:instrText>)/si', $field, $match)) {
$key = strtoupper($match[2]);
} else {
return $replace[0];
}

$sec = $this->temporarySectionName.'/'.$key;
if (isset($this->mergeData[$key])) {
/* success */
$newval = $this->mergeData[$key];
$this->mergeSuccess[$sec] = (isset($this->mergeSuccess[$sec])?$this->mergeSuccess[$sec]:0) + 1;
} else {
/* failure */
$newval = $key;
$this->mergeFailure[$sec] = (isset($this->mergeFailure[$sec])?$this->mergeFailure[$sec]:0) + 1;
}

$final = preg_replace('/(<w:t.*?>)(.+?)(<\/w:t>)/si', '${1}'.$newval.'${3}', $final);
return $final;
}


/**
* Returns array of all variables in template.
*
* @return string[]
Expand Down