2013-06-29 64 views
7

我已經嘗試了很多潛在的解決方案,但他們都沒有爲我工作。 最簡單的一個:如何使用php刪除文件的最後一行?

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

根本沒有做任何事情。我在這裏做錯了什麼?它是不同的,因爲它是一個HTML文件?

+0

請提供一些詳細信息 –

+0

您需要將$ file寫回到list.html中,以便實際更改存儲在磁盤上的文件 –

+0

您是否想要刪除最後一行並將其保存回磁盤? – angelsl

回答

9

這應該工作:

<?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 
$fp = fopen('filename.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 

?> 
+0

我在另一個網站上看過,但是當我嘗試它時,它複製了原始文檔,一切都出現了兩次。這有任何意義嗎? – jemtan990

+0

哦,我的天哪,我知道我做錯了什麼,這真的很愚蠢。我正在嘗試將數組寫入文件並同時追加新的信息。我需要fopen('list.html','w +');然後關閉,然後用'a'再次打開它。感謝所有的幫助!該解決方案確實有效。 – jemtan990

+0

我們如何從CSV @angezanetti中刪除第一行和最後一行? –

-2

您只能讀取文件,你現在需要寫入文件

查找到file_put_contents

+0

對不起,我應該使用更多的細節。我在與我正在編寫代碼的計算機不同的計算機上詢問此問題,因此我沒有包括所有內容。我寫了文件,但它沒有做任何事情。 – jemtan990

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 
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)); 
} 

呼叫這樣的功能:

trim_lines("filename.txt", 1); 

可變$path可以是文件或一個文件名的路徑。

相關問題