How to Compare DOCX Files in PHP

Cloudmersive
2 min readMay 3, 2024

After we make numerous rounds of revisions to a DOCX file, it’s beneficial to compare the final DOCX document to the original and highlight the differences.

Otherwise, we can easily lose sight of just how far an important document (e.g., a legal contract) has come from its original iteration.

Using the below PHP code examples, we can take advantage of a free API for comparing one DOCX document to another. The API response will produce a new DOCX file that clearly highlights the differences between the original DOCX document and the revised iteration.

Before we structure our API call, we should grab a free Cloudmersive API key to authorize our requests. This will allow us to make up to 800 API calls per month with no additional commitments.

With our API key ready, we can first install the PHP client via composer by executing the below command from the command line:

composer require cloudmersive/cloudmersive_document_convert_api_client

Next, we can use the below examples to call the function:

<?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\CompareDocumentApi(


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 (more than 2 can be supplied).

try {
$result = $apiInstance->compareDocumentDocx($input_file1, $input_file2);
print_r($result);
} catch (Exception $e) {
echo 'Exception when calling CompareDocumentApi->compareDocumentDocx: ', $e->getMessage(), PHP_EOL;
}
?>

That’s all there is to it — now we can easily compare two DOCX documents and highlight every difference between them.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.