With the development of information technology, file processing has become increasingly important in daily work. We often need to compare two files to identify differences for further processing. Using PHP's built-in functions, it's easy to create a simple file comparison feature. This article explains the implementation process in detail and provides code examples.
First, determine the paths of the two files to compare. Here, we assume the file names are file1.txt and file2.txt, both located in the same directory.
You can use the file_get_contents() function to read the file contents into variables:
$file1 = file_get_contents('file1.txt'); $file2 = file_get_contents('file2.txt');
To find differences between the two files, we compare their contents character by character using PHP string functions. The example code is as follows:
$diff = ''; $length = max(strlen($file1), strlen($file2)); for ($i = 0; $i < $length; $i++) { if (($file1[$i] ?? '') !== ($file2[$i] ?? '')) { $diff .= "{$file1[$i] ?? ' '} and {$file2[$i] ?? ' '} are different\n"; } }
In this code, we loop through each character of the two files and record any differences in the $diff variable. The null coalescing operator ?? is used to avoid errors if the files have different lengths.
Display the difference information on the page while preserving formatting for easy reading:
echo "<pre>{$diff}";
$file1 = file_get_contents('file1.txt'); $file2 = file_get_contents('file2.txt'); $diff = ''; $length = max(strlen($file1), strlen($file2)); for ($i = 0; $i < $length; $i++) { if (($file1[$i] ?? '') !== ($file2[$i] ?? '')) { $diff .= "{$file1[$i] ?? ' '} and {$file2[$i] ?? ' '} are different\n"; } } echo "<pre>{$diff}";
The above method demonstrates how to implement a basic file content comparison feature using PHP. In real projects, more complex comparison logic and optimizations may be required, such as line-by-line comparison and highlighting differences. However, this example provides a useful reference for beginners and quick implementations of file difference detection.