如果b.txt中不存在,php将a.txt中的行写入b.txt

如果b.txt中不存在,php将a.txt中的行写入b.txt,php,unique,fwrite,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); } ?> 至 $file = fopen("b.txt", "w"); 每次我刷新.php时,我都会得到包含相同数据的额

您好,我使用此代码将唯一行从文件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);
}
?>

 $file = fopen("b.txt", "w");
每次我刷新.php时,我都会得到包含相同数据的额外行(也是正常的)。我想知道是否有任何简单的解决方案可以使用

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

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

这应该可以完成以下工作:

$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);

您可以使用命令读取这两个文件,这样您将获得两个可以比较的数组,就像使用从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
"

你到底想干什么?也许还有更好的方法。@Amal Murali:标题说明了他想要什么,我用$u GET['v']和submit按钮存储数据。然后在console.php中,我将a.txt数据复制到b.txt数据,但仅复制唯一文件数组_unique。。。但正如我所写的,如果每次从b.txt中的a.txt获得唯一文本时都刷新console.php。。现在在b.txt中有两行相同的内容(每行刷新新内容-相同的数据行)。我想在b.txt中存储、写入数据,这在a.txt中是唯一的,但在b.txt中还没有。txt@machineaddict当前位置但它看起来像一个机器。当问题的根源似乎是另一个问题时,解决问题是没有用的。如果有更好的存储技术,并且不需要在之后进行唯一比较,那么所有这些都将被丢弃。a.txt中的内容:测试结果:测试两行相同的代码。还有,在“if(!in_array($line_a,$file_b)”…之后缺少一个“)”。第二次刷新console.php时,我得到了空页。第三次刷新给出了第一次的结果。@MatejMerc我真的不明白刷新的问题。只是尝试了代码(缺少括号)它工作正常…您可能会因为换行而出现问题,请尝试以下操作:
file('a.txt',file\u IGNORE\u NEW\u LINES)
并在
frwite:fwrite($file\u b\u to\u write,$line\u a)上添加换行符(或者之前使用PHP\u EOL,取决于您当前的文件格式)
$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);
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
"