如何使用PHP删除文件的最后一行?

13

我尝试了很多可能的解决方案,但它们都对我没有用。 最简单的一个:

$file = file('list.html');
array_pop($file);

这里好像什么都没做。我有做错什么吗?因为这是一个html文件所以情况不同吗?


请提供更多细节。 - Rick Slinkman
你需要将 $file 写回 list.html 才能实际更改存储在磁盘上的文件。 - Mark Baker
你的意思是要删除最后一行并将其保存回磁盘吗? - angelsl
5个回答

20
这应该可以运行:
<?php 

// load the data and delete the line from the array 
$lines = file('filename.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 

// write the new data to the file 
file_put_contents('filename.txt', $lines); 

我在另一个网站上看到过这个,但是当我尝试时,它复制了原始文档,所有内容都出现了两次。这有任何意义吗? - jemtan990
天啊,我终于发现自己错在哪里了,而且原因非常愚蠢。我一直试图将数组写入文件并同时追加新信息。我需要使用fopen('list.html', 'w+'); 然后关闭,再用'a'打开。感谢大家的帮助!这个解决方案确实可行。 - jemtan990
我们如何从CSV文件中删除第一行和最后一行呢,@angezanetti? - Noor M
  1. 你将失去文件中的所有换行符。
  2. 你将把整个文件存储在一个变量中。
- vladkras
  1. unset($var[count($var) - 1]) 不如 array_pop($var) 简洁优美。
  2. implode 函数中不需要声明 glue 参数为空。($implode($lines)
- mickmackusa

1
在一个简单的情况下,我使用以下代码:
$text = file_get_contents( 'FILE_PATH' );
$pos = strrpos( $text, PHP_EOL );
$text = substr( $text, 0, $pos );
file_put_contents( 'FILE_PATH', $text );

或者稍微扩展一下,检查文件是否以换行符结尾:
$text = file_get_contents( 'FILE_PATH' );
$offset = mb_substr( $text, -1 ) == PHP_EOL ? -2 : 0;
$pos = strrpos( $text, PHP_EOL, $offset );
$text = $offset === 0 ? substr( $text, 0, $pos ) : substr( $text, 0, $pos ) . PHP_EOL;
file_put_contents( 'FILE_PATH', $text );

0
我创建了一个函数来删除底部的x行。将$max设置为您想要删除的行数。
function trim_lines($path, $max) { 
  // Read the lines into an array
  $lines = file($path);
  // Setup counter for loop
  $counter = 0;
  while($counter < $max) {
    // array_pop removes the last element from an array
    array_pop($lines);
    // Increment the counter
    $counter++;
  }  // End loop
  // Write the trimmed lines to the file
  file_put_contents($path, implode('', $lines));
}

Call the function like this:

trim_lines("filename.txt", 1);

变量$path可以是文件路径或文件名。

0

在 PHP 中删除变量的第一行和最后一行:

使用 phpsh 交互式 shell:

php> $test = "line one\nline two\nline three\nline four";

php> $test = substr($test, (strpos($test, "\n")+1));

php> $test = substr($test, 0, strrpos($test, "\n"));

php> print $test;
line two
line three

你可能想表达的是“最后一个非空行”。如果是这样,请按照以下步骤操作:

请注意,在内容后面有三行空白行。这将在删除最后一行之前去除这些行:

php> $test = "line one\nline two\nline three\nline four\n\n\n";

php> $test = substr($test, 0, strrpos(trim($test), "\n"));

php> print $test;
line one
line two
line three

-3

你只是在读取文件,现在需要写入文件

可以查看 file_put_contents 等函数


对不起,我应该提供更多细节。我在另一台电脑上提出这个问题,所以没有包括所有内容。我已经写入文件,但它似乎没有任何作用。 - jemtan990

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