Forum Moderators: coopster

Message Too Old, No Replies

Delete lines from flatfile db by range of dates

Delete lines from flatfile db by range of dates

         

bobalooie

10:52 pm on Feb 22, 2009 (gmt 0)

10+ Year Member



Hello Friends:

I am trying to delete any lines from a flatfile database if they contain a datestamp older than 90 days from the present date.

My flatfile db has about a couple hundred records, one record per line... and there twenty fields per line, each delimited by a pipe ¦. The datestamp is in field 12 and is in the format
of mm/dd/yyyy.

I can delete lines based on "one date", shown in the script below... but I am at a loss how to delete all lines that are older than 90 days.

Could anyone offer suggestions or point me to a snippet? Any help would be gratefully appreciated. Thanks so much.

<?

$database = "data.txt";
$key = "¦01/06/2001¦";
$fc=file("$database");
$f=fopen("$database","w");
if (flock($f, LOCK_EX)) { // do an exclusive lock
foreach($fc as $line)
{
if (!strstr($line,$key)) //look for $key in each line
fputs($f,$line); //place $line back in file
flock($f, LOCK_UN); // release the lock
}
}
fclose($f);
echo "Line deleted";
?>

penders

10:00 am on Feb 23, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



At the moment you are doing a straight forward pattern match on your entire record as a string - there is no concept of individual fields. If you need to process all lines that are older than 90 days then you will need to examine field 12 specifically and turn it back into a date (that PHP understands). So, you need to make that extra step and explode() [uk.php.net] your record back into fields that you can easily process.

$fields = explode('¦',$line);

You could then further explode() field#12 ($fields[11] - starting at 0) into your month, day and year components. Use mktime() [uk.php.net] to turn this into a unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT) then subtract this from time() [uk.php.net] (the current unix timestamp). If the resultant value is > 7776000 (the number of seconds in 90 days... 60 x 60 x 24 x 90) then delete the line.

(Note: This forum converts the pipe into a different character! ... and Welcome to webmasterworld :)