[![mail merge][1] from a single template and a structured data source. The letter may be sent out to many recipients with small changes, such as a change of address or a change in the greeting line. It can also be used to generate business reports, purchase orders, receipts, catalogs, inventories, and invoices etc.

Aspose.Words Cloud Mail Merge allows you to generate documents from a template and XML in any language including .NET, Java, PHP, Ruby, Rails, Python, jQuery and many more. You can use it with any language or platform that supports REST. (Almost all platforms and languages support REST and provide native REST clients to work with REST APIs.)

This post covers mail merge in PHP, you can check Aspose.Words Cloud documentation for other languages. To execute mail merge, you need to upload a template to Aspose Cloud or any supported third party storage and then send a POST request (passing XML data in the request body) to generate documents based on template and data. The following steps describe the process in detail.

Decide which Type of Mail Merge to Execute

Aspose.Words Cloud supports simple mail merge and mail merge with regions. If you want to insert simple or non-repeating data, for example name, address and code fields on an envelope, or to and from fields in a letter, use simple mail merge (also called mail merge without regions).

If you are preparing reports, invoices and purchase orders, or similar documents, and want to insert tables, rows or repeating data, or if you want your documents to dynamically grow based on your input data, use mail merge with regions.

Prepare a Template

In order to prepare your template to perform a simple mail merge (without regions, similar to the classic mail merge available in Microsoft Word), insert one or more merge fields in the places you want to populate with data from the data source. See Simple Mail Merge Explained and Prepare a Document for more details.

To dynamically grow portions of the document, use mail merge with regions. To specify a mail merge region in the document, insert two mail merge fields to mark the beginning and end of the mail merge region. All document content included in a mail merge region are automatically repeated for every record in the data source (in most cases this is a table). See Mail Merge with Regions Explained and Prepare a Document for more details.

Format XML

If you want to execute simple mail merge and there are no «TableStart:TableName»«TableEnd:TableName» type merge fields in the Word document, use the following XML structure to send in the request body.

<?xml version="1.0" encoding="utf-8" ?>
<CollectionName>
    <field1>Value1</field1>
    <field2>Value2</field2>
</CollectionName> 

Note: You can select any text for CollectionName in XML but field names must match the names of the merge fields in the Word document.

To execute mail merge with regions when the merge fields are within «TableStart:TableName»«TableEnd:TableName» regions, use the following XML structure to send in the request body.

<?xml version="1.0" encoding="utf-8"?>
<CollectionName xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <ItemName>
        <field1>Value1</field1>
        <field2>Value2</field2>
    </ItemName>
    <ItemName>
        <field1>Value1</field1>
        <field2>Value2</field2>
    </ItemName>
</CollectionName> 

Note: You can select any text for CollectionName in your XML but ItemName must match TableStart and TableEnd region name (for example «TableStart:ItemName»«TableEnd:ItemName» in this case) and field names must match the names of the merge fields in your Word document.

Mail Merge using PHP REST

Before you execute mail merge, you need to upload your template Word file and XML data to Aspose Cloud or any supported third party storage. See Upload File examples for more details.

Once you upload your template and XML, you can use the following URI to execute mail merge:

https://apireference.aspose.cloud/words/#/MailMerge/ExecuteMailMerge

There are several optional parameters you can use with the above mentioned URI. All or specific parameters can be used according to your requirement. Following is the detail of these optional parameters.

  • withRegions – This parameter can be set to true if you want to execute mail merge with regions. See section 1 of the complete code.
  • mailMergeDataFile – This parameter can be set to specify the XML data file. See section 1 of the complete code.
  • cleanup – This parameter can be set specify different cleanup options e.g. if you want to remove empty paragraphs, unused fields and empty tables etc. See section 1 of the complete code and [executeMailMerge resource][2].
  • filename – This parameter can be used to specify name of the file generated as a result of mail merge.
  • storage – This parameter can be used to set storage name if you are using a third party storage.
  • folder – This parameter can be used to set the name/path of the folder where template file is uploaded.

After building the URI, go through the following steps:

  1. Set App SID and App Key and sign URI. See section 2 of the complete code and [Sign URI][3] method for more details.
  2. Send a POST request to Aspose Cloud service. See section 3 of the complete code and [ProcessCommand][4] method for more details.
  3. Get output file name from the response stream. See section 4 of the complete code.

The complete code follows.

 /**** Section 1 ****/

// Build URI to execute mail merge
$strURI = 'http://api.aspose.com/v1.1/words/Sample.docx/executeMailMerge?withRegions=true&mailMergeDataFile=Data.xml';
// Use the following URI if you want to remove EmptyParagraphs,UnusedRegions,UnusedFields and ContainingFields during mail merge
// $strURI = 'http://api.aspose.com/v1.1/words/Sample.docx/executeMailMerge?mailMergeDataFile=Data.xml&cleanup=EmptyParagraphs,UnusedRegions,UnusedFields,ContainingFields';
/**** End Section 1 ****/

/**** Section 2 ****/
$appSID  = "77****-****-****-****-80*********";
$appKey = "****************";

// Sign URI
$signedURI = Sign($strURI, $appSID, $appKey);
/**** End Section 2 ****/

/**** Section 3 ****/
$responseStream = ProcessCommand($signedURI, "POST", "", "");
/**** End Section 3 ****/

/**** Section 4 ****/
$json = json_decode($responseStream);
//build URI to download output DOC
$outputFileName = $json->Document->FileName;
/**** End Section 4 ****/ 

After executing mail merge, you can download the output file by following the [Download File][5] example.

Mail Merge using PHP SDK

If you want to use our PHP SDK to execute mail merge, you can download this SDK from [Aspose Cloud SDK for PHP][6]. In order to use PHP SDK, you need to perform following steps:

  • Set base product URI, App SID and App Key. See section 1 of the complete code.
  • Set output location, input file name and input XML. See section 2 of the complete code.
  • Upload input file. See section 3 of the complete code.
  • Create object of MailMerge class and call executeMailMerge method for simple mail merge and executeMailMergeWithRegions method for mail merge with regions. See section 4 of the complete code.

The complete code follows.

/**** Section 1 ****/

// Specify product URI Product::$baseProductUri = "http://api.aspose.com/v1.1"; //sepcify App SID AsposeApp::$appSID = "xxxxxxxxxxxxxxxxxxxxxxxx"; //sepcify App Key AsposeApp::$appKey = "xxxxxxxxxxxxxxxxxxxxxxxx";

/**** End Section 1 ****/

try{

/**** Section 2 ****/
AsposeApp::$outPutLocation = getcwd() . "/Output/";   $mainDocumentFile = getcwd() . "/Input/SimpleMerge.doc";   $mainDocument = basename($mainDocumentFile);   $xml = simplexml_load_file(getcwd() . "/Input/SimpleMerge.xml");
/**** End Section 2 ****/

/**** Section 3 ****/
//upload main document   echo "Uploading main document...<br />";   $folder = new Folder();   $folder->uploadFile($mainDocumentFile, "");   echo "Main document uploaded <br />";
/**** End Section 3 ****/

/**** Section 4 ****/
echo "Executing mail merge... <br />";   //create MailMerge object   $doc = new MailMerge();   $result = $doc->executeMailMerge($mainDocument, $xml->asXML());
/**** End Section 4 ****/ }

catch (Exception $e)
  {
    throw new Exception($e->getMessage());
  } 

Related Post:

Perform Mail Merge in a Word Document

[1]: https://blog.aspose.com/wp-content/uploads/sites/2/2013/12/asposeCloudAPIs.png “Aspose Cloud APIs”)](https://blog.aspose.com/wp-content/uploads/sites/2/2013/12/asposeCloudAPIs.png)Mail merge allows you to produce document (potentially large numbers of documents [2]: https://docs.aspose.cloud/display/wordscloud/Working+with+Mail+Merge [3]: http://www.aspose.com/docs/display/rest/REST+API+Methods [4]: http://www.aspose.com/docs/display/rest/REST+API+Methods [5]: http://www.aspose.com/docs/display/rest/Download+a+Particular+File [6]: https://github.com/asposeforcloud/Aspose_Cloud_SDK_For_PHP