How to Merge DOCX Files in PHP
We can easily merge two or more DOCX files in a quick, low-code operation using complementary PHP code examples.
Instead of writing a ton of new code, we’ll simply handle our DOCX merge using a free API. This will allow us to easily merge up to 10 DOCX files in a single request, taking a ton of extra coding (and future code maintenance) time off our hands.
We can structure our API call in a few quick steps. First, we can use the below command to install the PHP client via Composer:
composer require cloudmersive/cloudmersive_document_convert_api_client
Next, we can copy the below code to call our document merge function (each input DOCX file goes in an $input_file
variable):
<?php
require_once(__DIR__ . '/vendor/autoload.php');
// Configure API key authorization: Apikey
$config = Swagger\Client\Configuration::getDefaultConfiguration()->setApiKey('Apikey', 'YOUR_API_KEY');
$apiInstance = new Swagger\Client\Api\MergeDocumentApi(
new GuzzleHttp\Client(),
$config
);
$input_file1 = "/path/to/inputfile"; // \SplFileObject | First input file to perform the operation on.
$input_file2 = "/path/to/inputfile"; // \SplFileObject | Second input file to perform the operation on.
$input_file3 = "/path/to/inputfile"; // \SplFileObject | Third input file to perform the operation on.
$input_file4 = "/path/to/inputfile"; // \SplFileObject | Fourth input file to perform the operation on.
$input_file5 = "/path/to/inputfile"; // \SplFileObject | Fifth input file to perform the operation on.
$input_file6 = "/path/to/inputfile"; // \SplFileObject | Sixth input file to perform the operation on.
$input_file7 = "/path/to/inputfile"; // \SplFileObject | Seventh input file to perform the operation on.
$input_file8 = "/path/to/inputfile"; // \SplFileObject | Eighth input file to perform the operation on.
$input_file9 = "/path/to/inputfile"; // \SplFileObject | Ninth input file to perform the operation on.
$input_file10 = "/path/to/inputfile"; // \SplFileObject | Tenth input file to perform the operation on.
try {
$result = $apiInstance->mergeDocumentDocxMulti($input_file1, $input_file2, $input_file3, $input_file4, $input_file5, $input_file6, $input_file7, $input_file8, $input_file9, $input_file10);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling MergeDocumentApi->mergeDocumentDocxMulti: ', $e->getMessage(), PHP_EOL;
}
?>
That’s all the code we’ll need! Now we just need to authorize our API requests by supplying a free Cloudmersive API key in the $config
snippet, and we’re all set. A free API key will allow us to make up to 800 API calls per month with zero commitments (our total will just reset the following month once we reach it).
All done!