开发者

Extracting from a DYNAMIC text file _ basic PHP problem

开发者 https://www.devze.com 2023-02-20 17:51 出处:网络
I am trying to extract contents from a txt file. This file is dynamic because data keeps appending to it everytime the loop is executed.

I am trying to extract contents from a txt file. This file is dynamic because data keeps appending to it everytime the loop is executed. Inside this loop rests my logic for extrac开发者_如何学Cting contents from file, as follows...

$length = filesize($filename);  
fseek($fd,$previousLength);  
$contents = fread($fd,(($length - $previousLength)));  
$previousLength = $length;  

i.e, I AM trying to read only the data that got appended, in the last loop ... and not the data that was previously written. EXAMPLE... A txt adds ONE everytime a loop is run.. i.e consider

114134, 144, 1443, 1433 ... 
(n of these written every once in loop ) ... 

If I read n values , say

114134, 144 ... 

in the first loop ...

next time, I need to read only

1443, 1443 and NOT 114134, 144 ....

fread() fails miserably here ,and fseek doesn't help ( ref. my code above) ...

I DON"T KNOW WHY !! help needed asap ..

Thanks


If you have opened the file in append mode then the man page for fseek says:

If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

The following code has a few modifications. I had a few problems with the length - fread does require it, but i decided to use fgets to avoid it. This would stop on newline characters but has the handy feature of reading the entire remaining contents of the file otherwise. There may be a better way of doing this, but this does work.

<?php
$filename = 'loopFile.txt';
$previousLength = 0;
$n = 0;

$fw = fopen($filename, 'a+');
$fr = fopen($filename, 'r');

for ($i=0; $i < 15; $i++)
{
   // Put a random number of numbers into the file.
   $numberOfNumbers = rand(0, 5);

   for ($writeCount = 0; $writeCount < $numberOfNumbers; $writeCount++)
   {
      fwrite($fw, $i . '_' . $n++ . ', ');
   }

   fseek($fr, $previousLength);  
   $contents = fgets($fr);

   if (!empty($contents))
   {
      echo 'On iteration: ' . $i . ' read: ' . $contents . "\n";
   }
   else
   {
      echo 'On iteration: ' . $i . ' no new data appended to file.' . "\n";
   }

   $previousLength += strlen($contents);  
}

fclose($fw);
fclose($fr);

?>


Not sure if I got this right, but you're reading data from a file that you're appending in the same loop?

Is the data that you write all seperate lines added to the file? You can look at the file() command instead, it reads every line into an array... You can then array_slice() the right lines out of the array by counting lines in before situation, then the after situation.

0

精彩评论

暂无评论...
验证码 换一张
取 消