php如果在b.txt中不存在,则从a.txt写入行到b.txt

时间:2014-07-18 14:02:57

标签: php unique fwrite

您好我使用此代码将文件a.txt中的唯一行复制到b.txt:

<?php
function fileopen($file)
{
$file1 = fopen($file, "r") or ("Unable to open file");
while (!feof($file1))
{
echo fgets($file1);
}
fclose($file1);
}
?>

并在body标签中插入:

<?php
$lines = file("http://127.0.0.1/a.txt");
$lines = array_unique($lines);
$file = fopen("b.txt", "a");
fwrite($file, implode("\r\n", $lines));
fclose($file);
?>

效果很好但是如果你删除了#34; a.txt&#34;并再次打开.php文件我的b.txt文件为空(这是正常的)。如果我改变

 $file = fopen("b.txt", "a");

 $file = fopen("b.txt", "w");

每次刷新.php我都会获得具有相同数据的额外行(也是正常的)。我想知道是否有任何SIMPLE解决方案可供使用

$file = fopen("b.txt", "w");

但只有在数据不在b.txt文件中时才写入数据。

2 个答案:

答案 0 :(得分:1)

这应该做的工作:

$file_a = array_unique(file('a.txt'));
$file_b = array_unique(file('b.txt')); // Note : I supposed array_unique here too

$file_b_to_write = fopen('b.txt', 'w');

foreach ($file_a as $line_a) {
     if (!in_array($line_a, $file_b)) {
         fwrite($file_b_to_write, $line_a);
     }
}

fclose($file_b_to_write);

答案 1 :(得分:0)

您可以使用file命令读取这两个文件,这样您就可以得到两个可以比较的数组,例如使用array_diff从b.txt中获取缺失的行并将其添加到b.txt。使用此解决方案时,您必须注意处理大文件时的内存使用情况。

以下是我建议的实施示例:

php > var_dump(file_get_contents('a.txt'));
string(4) "foo
"
php > var_dump(file_get_contents('b.txt'));
string(4) "bar
"
php > $a = file('a.txt');
php > $b = file('b.txt');
php > $missing = array_diff($a, $b);
php > var_dump($missing);
array(1) {
  [0] =>
  string(4) "foo
"
}
php > file_put_contents('b.txt', $missing, FILE_APPEND);
php > var_dump(file_get_contents('b.txt'));
string(8) "bar
foo
"