使用PHP根据时间从.txt文件中删除行

Im working on a small project.

What Im trying to Do, is Have a PHP File, Delete Lines from a .txt file based on time

The .txt file will be formatted like this

Content | Time (Unix Time)
Content | Time (Unix Time)

Everytime the php file is executed i want it to delete everyline thats = or less than the current Time

Ive tried using google, and Have had no luck, I am pulling the time from one source. so that wont be a problem, Just the PHP Part.

Is there a snippet? or is this going to be difficult.

There are many ways to handle this... It is actually quite easy unless your file is really large. This method isn't the most memory efficient, but it is probably the easiest.

Read the file into an array of lines with file(), loop over them and explode each on |. Add the line to an output array if the timestamp is newer than the current time.

In the end, write the file back out with the output array's values:

$output = array();
// Read the file into an array of lines:
$lines = file('yourfile.txt');
// Store the current time
$now = time();

foreach ($lines as $line) {
  // Split on |
  list($content, $time) = explode("|", $line);
  if ($time > $now) {
     // Keep the line in the output array:
     $output[] = $line;
  }
  // Otherwise do nothing with it
}

// Implode it back to a string and write to file:
$outstring = implode("
", $output);
file_put_contents("yourfile.txt", $outstring);

Make sure yourfile.txt has the appropriate write permissions for your web server user, or whatever user is executing this script.

You may want to look into fgetcsv and fputcsv. You can loop through all of the lines in the file using the former, filter through the ones that don't follow your condition, and put all the ones that haven't been caught by the filter back into the file.

<?php
$filtered = array();
if($handle = fopen("data.txt", "r")){
    while($data = fgetcsv($handle, 0, "|")){
        if($data[1] > time()){
            $filtered[] = $data;
        }
    }
    fclose($handle);
}
if($handle = fopen("data.txt", "w")){
    for($i = 0; $i < count($filtered); $i += 1){
        fputcsv($handle, $filtered[$i], "|");
    }
}
?>

To improve on @Michael's answer, instead of keeping everything in memory, use two file streams and write the lines matching form the first to the second. This will allow you to process arbitarly large files. You can also write the stdout as most applications will do by default, and redirect the output to a file instead.

$input = fopen("file.txt", "rb");
$output = fopen("output.txt", "wb");
$now = time();

while ($row = fgets($input))
{
    list($content, $time) = explode("|", $row);

    if ($time > $now)
    {
        // change to echo to write to stdout
        fwrite($output, $row);
    }
}

fclose($input);
fclose($output);