2

When saving revision #7 of a textfile with PHP, I use:

<?php 
  $file = fopen("data/myfile-revision7", 'w');
  fwrite($file, $data);
  fclose($file);
?>

But instead of saving the whole $data again and again for every revision, I would prefer to store the differences between myfile-revision1 and myfile-revision7.

Is there a function included in PHP that would compute the diff of 2 text files?


Note: If later, I want to get the full myfile-revision7 textfile again, how can I generate this file back, with the diff data?

hichris123
  • 10,145
  • 15
  • 56
  • 70
Basj
  • 41,386
  • 99
  • 383
  • 673
  • perhaps you could make use of the [file_get_contents](http://php.net/manual/en/function.file-get-contents.php) function to filter out the text which is already saved elsewhere. and put the remaining text in a new file. – Azrael Oct 01 '14 at 13:36
  • 1
    have you looked into xdiff? http://php.net/manual/en/intro.xdiff.php – VF_ Oct 01 '14 at 13:40
  • You are basically asking for a tool recommendation here, making this off-topic. You might google `PHP diff library` and see what turns up (like `xdiff` perhaps). – Mike Brant Oct 01 '14 at 13:41

1 Answers1

2

You probably want to use xdiff_file_diff function. Here is the documentation.

<?php
  $old = 'data/myfile-revision1';
  $new = 'data/myfile-revision7';
  $output = 'data/rev-1-7.diff'

  xdiff_file_diff($old, $new, $output);
?>
JunYoung Gwak
  • 2,967
  • 3
  • 21
  • 35
  • Thanks! Unfortunately I cannot use `xdiff_file_diff` because I cannot install `libxdiff` on my shared hosting (I'm not root)... Do you see another solution ? – Basj Oct 01 '14 at 19:22
  • I think you can read two files and then take diff using external library like this: [http://www.raymondhill.net/finediff/viewdiff-ex.php](http://www.raymondhill.net/finediff/viewdiff-ex.php). Or, you can make system call `exec('diff revision1 revision2 > rev-1-7.diff')` if your shared hosting allows it. – JunYoung Gwak Oct 01 '14 at 19:35
  • I think it seems to work with `` But I have this answer : `\ No newline at end of file` : any idea ? – Basj Oct 01 '14 at 19:44
  • Try to write a file with `implode("\r\n", $diff)`. – JunYoung Gwak Oct 01 '14 at 20:20
  • the standard `diff` / `patch` Linux tools finally won't work for my usage, because they are designed for diff **between lines**... But I only have one big line containing lots of text data... not lines... Another kind of `diff` in mind for this ? – Basj Oct 01 '14 at 20:36