PHP将b.txt中不存在的行写入b.txt


php write line from a.txt to b.txt if don not exist in b.txt

嗨,我用这段代码将唯一的行从文件a.t txt复制到b.t 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);
?>

它工作得很好,但如果你删除"a.t txt"中的内容并再次打开。php文件,我的b.t txt文件是空的(这是正常的)。如果我改变

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

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

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

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

这应该可以完成工作:

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

您可以使用file命令读取这两个文件,这样您将获得两个可以比较的数组,例如使用array_diff从b.t txt中获取缺失的行并将其添加到b.t 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
"