-
-
Save damijanc/ce49bfc64629f293edd9 to your computer and use it in GitHub Desktop.
using unix system to make file diff
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @brief Find the difference between two strings, lines assumed to be separated by "\n| | |
* @param $new string The new string | |
* @param $old string The old string | |
* @return string Human-readable output as produced by the Unix diff command, | |
* or "No changes" if the strings are the same. | |
* @throws Exception | |
*/ | |
public function diff($new, $old) | |
{ | |
$oldfile = '/tmp/old.txt'; | |
$newfile = '/tmp/new.txt'; | |
if (! file_put_contents($oldfile, $old)) { | |
throw new \Exception('diff failed to write temporary file: ' . | |
print_r(error_get_last(), true)); | |
} | |
if (! file_put_contents($newfile, $new)) { | |
throw new \Exception('diff failed to write temporary file: ' . | |
print_r(error_get_last(), true)); | |
} | |
$answer = array(); | |
$cmd = "diff $newfile $oldfile"; | |
exec($cmd, $answer, $retcode); | |
unlink($newfile); | |
unlink($oldfile); | |
if ($retcode != 0) { | |
throw new \Exception('diff failed with return code ' . $retcode); | |
} | |
if (empty($answer)) { | |
return 'No changes'; | |
} else { | |
return implode("\n", $answer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment