~bohwaz/blog/

Avec de vrais morceaux de 2.0 !

simpleDiff : a lightweight and independent diff library for PHP

It's been a long time since I've been looking for an independent library to do visual diffs in PHP. I looked at existing works, like things used in MediaWiki (daisydiff), PEAR Text_Diff or phpwiki, but each implementation is either slow, requires more than one file to include, is too big or have old horrible php3 code.

So I decided to make my own implementation in just one file, fast, easy to use, lightweight and independent. The idea is pretty simple, it uses a diff implementation created by Daniel Unterberger and Nils Knappmeier. This function just generates a traditional diff (like the GNU command-line utility), then my class creates an easy-to-use array from that. Basically it's just a parser that renders a traditional diff in a php array.

So here goes the code : http://svn.kd2.org/svn/misc/libs/diff/ (the lib itself is only 14K!)

It's actually pretty easy to use. Just try that :

<?php
require 'class.simplediff.php';
$text1 = "One line
Two lines
Three lines";
$text2 = "One line
Changed line
Three lines
New line";
$diff = simpleDiff::diff($text1, $text2);
echo $diff;
?>

It will produce a traditional diff text, like the GNU diff utility. Now use that diff in diff_to_array method :

<?php
$array_diff = simpleDiff::diff_to_array($diff, $text1, $text2);
print_r($array_diff);
?>

And here goes an easier to use PHP array of differences :

Array

(

   [0] => Array
       (
           [0] => 0
           [1] => One line
           [2] => One line
       )

   [1] => Array
       (
           [0] => 2
           [1] => Two lines
           [2] => Changed line
       )

   [2] => Array
       (
           [0] => 2
           [1] => Three lines
           [2] => Three lines
       )

   [3] => Array
       (
           [0] => 1
           [1] => 
           [2] => New line
       )

)

As you can notice, each line is a row in the array, and that line is an array, where the first element is the change type (you can check that against simpleDiff::INS, simpleDiff::CHANGED, etc.). Pretty easy, nope?

The class can also emulate patch and wdiff utilities, could be useful.

It's pretty easy to use it to make a good-looking page of differences between two texts, check my example : http://dev.kd2.org/misc/diff/example.php (source code). And don't forget to check the readme file also.

Write a comment
(optional)
(optional)
(mandatory)
   _       _ _ _ _      
  (_) __ _(_) | (_)_ __ 
  | |/ _` | | | | | '__|
  | | (_| | | | | | |   
 _/ |\__,_|_|_|_|_|_|   
|__/                    
(mandatory)

URLs will create links automatically.
Allowed HTML tags: <blockquote> <cite> <pre> <code> <var> <strong> <em> <del> <ins> <kbd> <samp> <abbr>

Gama

Great. This is what I've looking for. I have used it in my final proyect degree (a web cooperative Latex editor) to compare between diferent document versions.

Thanks a lot :)