|
|
2#

楼主 |
发表于 2007-9-24 22:28:21
|
只看该作者

初看起来,这段脚本相当简单。在Text_Diff软件包中有两个基本的类:Text_Diff(),它执行比较并返回diff输出;和Text_Diff_Renderer(),它把diff输出格式化成一个易于理解的格式。特别要指出的是,Text_Diff()对象必须用进行比较的两个文件的内容(而不是位置)进行初始化。
上述脚本首先初始化这两个对象,利用PHP的file()函数把每个文件的内容提取成一系列的数组。然后用Text_Renderer()对象以标准的diff格式提交输出,生成任何UNIX开发者都熟悉的结果:
2c2
<banana
---
>bat
7,8c7,12
<grape
<horseradish
---
>peach
>pear
>
>
>
>zebra
增加输出结果的可读性
现在,除非你在解码diff结果方面拥有丰富经验,上述的输出结果并不是特别容易理解。因此Text_Diff提供许多选项,把这个输出重新格式化为更容易读取的格式。这些选项包含在Text_Diff_Renderer()对象的子类中,通过它们可以用统一的或内置的格式查看比较结果。
下面的脚本(列表D)对前面的例子进行了一些修改,以说明统一格式:
列表D
<html>
<head></head>
<body>
<pre>
<?php
// adjust file paths as per your local configuration!
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/unified.php";
// define files to compare
$file1 = "data1.txt";
$file2 = "data2.txt";
// perform diff, print output
$diff = &new Text_Diff(file($file1), file($file2));
$renderer = &new Text_Diff_Renderer_unified();
echo $renderer->render($diff);
?>
</pre>
</body>
</html>
注意在初始化renderer时调用了适当的子类。
以下为输出结果:
@@ -1,8 +1,12 @@
apple
-banana
+bat
cantaloupe
drumstick
enchilada
fig
-grape
-horseradish
+peach
+pear
+
+
+
+zebra |
|