Delete last blank line txt php

1

I have a txt file and I need to delete the last line, but it is blank.

I tried the code below and it erases only the top line of the last one that would be the one that is blank.

Follow the code below:

$lines = file('file.txt'); 
$last = sizeof($lines) - 1 ; 
unset($lines[$last]); 


$fp = fopen('file.txt', 'w'); 
fwrite($fp, implode('', $lines)); 
fclose($fp); 
    
asked by anonymous 07.11.2016 / 19:08

1 answer

2

That will solve. Any blank line will be removed. Remember that a space is not a blank line, so if so, modify the values of the array that have spaces.

<?php 
$lines = file('file.txt',FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 
$fp = fopen('file.txt', 'w'); 
fwrite($fp, implode(PHP_EOL, $lines)); 
fclose($fp); 
    
08.11.2016 / 14:40