PHP输出后循环翻转txt文件删除行

时间:2017-04-09 18:15:57

标签: php

我有一个PHP脚本,我循环遍历文本文件中的所有行。如何在读取后删除该行,因此在脚本结束时,所有已输出的行都将从文件中删除...

$file = $dataDoc['file'];
if(is_file($file)){
     $contents = file($file);
     foreach($contents as $line) {
        echo $line . "\n";
        // Delete line here and keep looping over the rest of the lines...
     }
}

2 个答案:

答案 0 :(得分:1)

$file = $dataDoc['file'];
if(is_file($file)){
     $contents = file($file);
     foreach($contents as $i => $line) {
        echo $line . "\n";
        unset($contents[$i]);
        fopen($file, 'w');
        fwrite(implode('\n', $contents));
        fclose($file);
     }
}

您要从$ contents数组中删除的文件中读取的每一行,然后重写没有该行的文件。这不是非常有效,但只是一种方法。

答案 1 :(得分:-1)

简单的解决方案可以是:

$contents = file($file);
foreach($contents as &$line) {   // add `&` to modify source line
    echo $line . "\n";

    if (/*Some case is true*/) {
        $line = null;            // unset a line if needed
    }
}

// lines that are NULL will not be written to a file
$writeRes = file_put_contents($file, $contents);