PHP library to generate code diff (github style)?
To add my two cents here...
Unfortunately, there are no really good diff libraries for displaying/generating diffs in PHP. That said, I recently did find a circuitous way to do this using PHP. The solution involved:
- A pure JavaScript approach for rendering the Diff
- Shelling out to
git
with PHP to generate the Diff to render
First, there is an excellent JavaScript library for rendering GitHub-style diffs called diff2html. This renders diffs very cleanly and with modern styling. However diff2html
requires a true git diff to render as it is intended to literally render git diffs--just like GitHub.
If we let diff2html handle the rendering of the diff, then all we have left to do is create the git diff to have it render.
To do that in PHP, you can shell out to the local git
binary running on the server. You can use git
to calculate a diff on two arbitrary files using the --no-index
option. You can also specify how many lines before/after the found diffs to return with the -U
option.
On the server it would look something like this:
// File names to save data to diff in$leftFile = '/tmp/fileA.txt'; $rightFile = '/tmp/fileB.txt';file_put_contents($leftFile, $leftData);file_put_contents($rightFile, $rightData);// Generate git diff and save shell output$diff = shell_exec("git diff -U1000 --no-index $leftFile $rightFile");// Strip off first line of output$diff = substr($diff, strpos($diff, "\n"));// Delete the files we just createdunlink($leftFile);unlink($rightFile);
Then you need to get $diff
back to the front-end. You should review the docs for diff2html
but the end result will look something like this in JavaScript (assuming you pass $diff
as diffString
):
function renderDiff(el, diffString) { var diff2htmlUi = new Diff2HtmlUI({diff: diffString}); diff2htmlUi.draw(el);}
I think what you're looking for is xdiff
.
xdiff extension enables you to create and apply patch files containing differences between different revisions of files.
This extension supports two modes of operation - on strings and on files, as well as two different patch formats - unified and binary. Unified patches are excellent for text files as they are human-readable and easy to review. For binary files like archives or images, binary patches will be adequate choice as they are binary safe and handle non-printable characters well.