如何在PHP中从文本文件中删除第一行

3
我将尝试制作一个简单的PHP程序,用于读取并删除文本文件的第一行。
目前我已经有了以下代码:
 <?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();

?>

代码仅适用于text.txt中的前两行,但当它应读取第三行时,代码停止工作。请问有何建议?
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);

感谢ghostdog74提供的解决方案,链接


正是我所需要的。谢谢。 - Robert
@Robert 好的,如果回答解决了您的问题,您可以批准它。 - Ghostman
所以即使你知道这是一个重复的问题! - RiggsFolly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接