PHP文件写 - 最大行数

时间:2012-10-22 15:46:10

标签: php file append max fopen

如何限制在文件中写入,如果达到限制则删除最后一行..

例如,这是一个文件:

Line 3
Line 2
Line 1

我想最大限度地将它排成3行..所以当我使用任何追加函数写一个新行时它会删除最后一行..假设我刚写了一个新行(第4行)..所以它去了到最后一个并删除它,结果应该是:

Line 4
Line 3
Line 2

对于新的书面行(第5行):

Line 5
Line 4
Line 3

数字行不是必需的,我只想删除最后一行,如果有一个新添加的行通过追加函数(file_put_contents / fwrite)并且最大值为3或我给出的特定数字

4 个答案:

答案 0 :(得分:3)

你可以尝试

$max = 3;
$file = "log.txt";
addNew($file, "New Line at : " . time());

使用的功能

function addNew($fileName, $line, $max = 3) {
    // Remove Empty Spaces
    $file = array_filter(array_map("trim", file($fileName)));

    // Make Sure you always have maximum number of lines
    $file = array_slice($file, 0, $max);

    // Remove any extra line 
    count($file) >= $max and array_shift($file);

    // Add new Line
    array_push($file, $line);

    // Save Result
    file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));
}

答案 1 :(得分:1)

这是一种方式:

  1. 使用file()将文件的行读入数组
  2. 使用count()确定数组中是否有超过3个元素。如果是这样:
    1. 使用array_pop()
    2. 删除数组的最后一个元素
    3. 使用array_unshift()将元素(新行)添加到数组的前面
    4. 使用数组行覆盖文件
  3. 示例:

    $file_name = 'file.txt';
    
    $max_lines = 3;              #maximum number of lines you want the file to have
    
    $new_line = 'Line 4';               #content of the new line to add to the file
    
    $file_lines = file($file_name);     #read the file's lines into an array
    
    #remove elements (lines) from the end of the
    #array until there's one less than $max_lines
    while(count($file_lines) >= $max_lines) {    
        #remove the last line from the array
        array_pop($file_lines);
    }
    
    #add the new line to the front of the array
    array_unshift($file_lines, $new_line);
    
    #write the lines to the file
    $fp = fopen($file_name, 'w');           #'w' to overwrite the file
    fwrite($fp, implode('', $file_lines)); 
    fclose($fp); 
    

答案 2 :(得分:0)

试试这个。

<?php

// load the data and delete the line from the array 

$lines = file('filename.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 

$fp = fopen('filename.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

?>

答案 3 :(得分:0)

Baba's回复修改;这段代码会在文件的开头写下新行,并且会删除最后一行以保持3行。

<?php
function addNew($fileName, $line, $max) {
    // Remove Empty Spaces
    $file = array_filter(array_map("trim", file($fileName)));

    // Make Sure you always have maximum number of lines
    $file = array_slice($file, 0, --$max);

    // Remove any extra line and adding the new line
    count($file) >= $max and array_unshift($file, $line);

// Save Result
file_put_contents($fileName, implode(PHP_EOL, array_filter($file)));
}

// Number of lines
$max = 3;
// The file must exist with at least 2 lines on it
$file = "log.txt";
addNew($file, "New Line at : " . time(), $max);

?>