使用php删除除前20行之外的所有行
如何使用php从文本文件中删除除前20行之外的每一行?抱歉,误读了问题使用php删除除前20行之外的所有行,php,file,truncate,lines,Php,File,Truncate,Lines,如何使用php从文本文件中删除除前20行之外的每一行?抱歉,误读了问题 $filename = "blah.txt"; $lines = file($filename); $data = ""; for ($i = 0; $i < 20; $i++) { $data .= $lines[$i] . PHP_EOL; } file_put_contents($filename, $data); $filename=“blah.txt”; $lines=文件($filename);
$filename = "blah.txt";
$lines = file($filename);
$data = "";
for ($i = 0; $i < 20; $i++) {
$data .= $lines[$i] . PHP_EOL;
}
file_put_contents($filename, $data);
$filename=“blah.txt”;
$lines=文件($filename);
$data=“”;
对于($i=0;$i<20;$i++){
$data.=$lines[$i].PHP\u EOL;
}
文件内容($filename,$data);
如果可以将整个文件加载到内存中,则可以执行以下操作:
// read the file in an array.
$file = file($filename);
// slice first 20 elements.
$file = array_slice($file,0,20);
// write back to file after joining.
file_put_contents($filename,implode("",$file));
更好的解决方案是使用函数,该函数获取文件句柄和文件的新大小(以字节为单位),如下所示:
// open the file in read-write mode.
$handle = fopen($filename, 'r+');
if(!$handle) {
// die here.
}
// new length of the file.
$length = 0;
// line count.
$count = 0;
// read line by line.
while (($buffer = fgets($handle)) !== false) {
// increment line count.
++$count;
// if count exceeds limit..break.
if($count > 20) {
break;
}
// add the current line length to final length.
$length += strlen($buffer);
}
// truncate the file to new file length.
ftruncate($handle, $length);
// close the file.
fclose($handle);
比如:
$lines_array = file("yourFile.txt");
$new_output = "";
for ($i=0; $i<20; $i++){
$new_output .= $lines_array[$i];
}
file_put_contents("yourFile.txt", $new_output);
$lines\u array=file(“yourFile.txt”);
$new_output=“”;
对于($i=0;$i,对于可以使用的内存高效解决方案
$file = new SplFileObject('/path/to/file.txt', 'a+');
$file->seek(19); // zero-based, hence 19 is line 20
$file->ftruncate($file->ftell());
在不占用大量内存的情况下,这也可以正常工作
$result = '';
$file = fopen('/path/to/file.txt', 'r');
for ($i = 0; $i < 20; $i++)
{
$result .= fgets($file);
}
fclose($file);
file_put_contents('/path/to/file.txt', $result);
$result='';
$file=fopen('/path/to/file.txt',r');
对于($i=0;$i<20;$i++)
{
$result.=fgets($file);
}
fclose($文件);
文件内容('/path/to/file.txt',$result);
你也应该自己做一些研究。这个网站是对其他资源的补充,而不是互联网其他部分的替代。人们很乐意提供帮助,但是,你也必须采取一些步骤来帮助自己。我想这会给你一个文件,除了前20行以外的所有内容。如果我理解正确,@Ahsan只需要前20行。这看起来更好,但您最好将$i设置为<20,否则您将阅读21行:)您的想法是正确的。您可以使用file()将内容读取到数组中,这样就不必手动分解()数据。您不需要知道第20行的字节计数吗?我对fopen()不够熟悉,至于它是否也会将整个文件放入内存,但如果fopen()使用的内存较少,则可以将其与fgets()一起用于前二十行