3

I try to make a simple php to read and delete first line from a text file.

So far I got the code:

 <?php
$myfile = fopen("text.txt", "r") or die("Unable to open file!");
$ch=1;




while(!feof($myfile)) {
  $dataline= fgets($myfile);
  $listes = explode("\n",file_get_contents("text.txt"));
  $poc = $listes[0];
  if($ch == 2){
  $gol = str_replace(' ', ' ', $dataline)."\n";
  $fh = fopen("newtext.txt",'a');
  fputs($fh,  $gol);
  fclose($fh);
  chmod("newtext.txt", 0777);
  }
  $ch = 2;
}
unlink("text.txt");
copy("newtext.txt", "text.txt");
chmod("text.txt", 0777);
unlink("newtext.txt");
fclose($myfile);

echo $poc;
flush();

?>

The code is working only for the first two lines in text.txt but when it should read the third line the code stop working. Any advice please.

0

1 Answer 1

2
$handle = fopen("file", "r");
$first = fgets($handle,2048); #get first line.
$outfile="temp";
$o = fopen($outfile,"w");
while (!feof($handle)) {
    $buffer = fgets($handle,2048);
    fwrite($o,$buffer);
}
fclose($handle);
fclose($o);
rename($outfile,$file);

credits to ghostdog74 for this solution link

3
  • Just what I've needed. Thank you.
    – Robert
    Feb 29, 2016 at 10:19
  • @Robert ok then u can approve the answer if it had solved your problem
    – Ghostman
    Feb 29, 2016 at 10:20
  • So even you know this was a duplicate question!
    – RiggsFolly
    Feb 29, 2016 at 10:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.