分两步求解:
获取行:获取行后执行https://stackoverflow.com/a/51350572/8524395
:
我有一个很大的文件,我想从这个文件的末尾提取1000行,然后删除它们。
我目前使用的是:
function deleteLineInFile($file,$string)
{
$i=0;
$array=array();
$read = fopen($file, "r") or die("can't open the file");
while(!feof($read)) {
$array[$i] = fgets($read);
++$i;
}
fclose($read);
$write = fopen($file, "w") or die("can't open the file");
foreach($array as $a) {
if(!strstr($a,$string)) fwrite($write,$a);
}
fclose($write);
}
$goods = '';
$file = file("../products/".$PidFileName);
for ($i = max(0, count($file)-1001); $i < count($file); $i++) {
$goods = $goods.$file[$i] . '<br />';
deleteLineInFile("../products/".$PidFileName, $file[$i]);
}
我想保存我在$goods
中得到的行
但是,由于文件大小,它会超时。
发布于 2018-07-16 01:29:07
如果你想从EOF中获得N行,你可以使用SPLFileObject (在PHP5.1中添加):
$num_to_cut = 1000; // must be an integer and not a string
$new_file = new SplFileObject("limited_test.txt", "w");
$old_file = new SplFileObject('test.txt');
// here we get count of lines: go to EOF and get line number
$old_file->seek($old_file->getSize());
$linesTotal = $old_file->key()+1;
// and write data to new file
foreach( new LimitIterator($old_file, $linesTotal-$num_to_cut) as $line) {
$new_file->fwrite($line);
}
发布于 2018-07-17 16:52:45
要在从大文件中获取行后删除它们,请执行以下操作:
最好的方法是使用sed
|,但是如果您没有使用exec()
函数的权限,那么这个函数是可以使用的。
function replace_file($path, $string, $replace)
{
set_time_limit(0);
if (is_file($path) === true)
{
$file = fopen($path, 'r');
$temp = tempnam('./', 'tmp');
if (is_resource($file) === true)
{
while (feof($file) === false)
{
file_put_contents($temp, str_replace($string, $replace, fgets($file)), FILE_APPEND);
}
fclose($file);
}
unlink($path);
}
return rename($temp, $path);
}
函数的来源:https://stackoverflow.com/a/2159135/8524395
要删除这一行,请像这样使用它:
replace_file('myfile.txt', 'RemoveThisPlease', '');
$line
https://stackoverflow.com/questions/51350234
复制相似问题