How to open a file and remove the last line?

2019-08-05 20:18发布

问题:

I am looking to open up a file, grab the last line in the file where the line = "?>", which is the closing tag for a php document. Than I am wanting to append data into it and add back in the "?>" to the very last line.

I've been trying a few approaches, but I'm not having any luck.

Here's what I got so far, as I am reading from a zip file. Though I know this is all wrong, just needing some help with this please...

// Open for reading is all we can do with zips and is all we need.
if (zip_entry_open($zipOpen, $zipFile, "r"))
{
    $fstream = zip_entry_read($zipFile, zip_entry_filesize($zipFile));
    // Strip out any php tags from here.  A Bit weak, but we can improve this later.
    $fstream = str_replace(array('?>', '<?php', '<?'), '', $fstream) . '?>';

    $fp = fopen($curr_lang_file, 'r+');

    while (!feof($fp))
    {
        $output = fgets($fp, 16384);
        if (trim($output) == '?>')
            break;
    }

    fclose($fp);
    file_put_contents($curr_lang_file, $fstream, FILE_APPEND);
}

$curr_lang_file is a filepath string to the actual file that needs to have the fstream appended to it, but after we remove the last line that equals '?>'

Ok, I actually made a few changes, and it seems to work, BUT it now copies the data in there twice... arggg, so each line in the file is now in there 2 times :(

Ok, removed the fwrite, though now it is appending it at the bottom, just below the ?>

OMG, I just need everything up to the last line, isn't there a way to do this??? I don't need "?>"

回答1:

A simple way with the file on the filesystem:

<?php

$path = "file.txt";
$content = file($path); // Parse file into an array by newline
$data = array_pop($content);

if (trim($data) == '?>') {
    $content[] = 'echo "... again";';
    $content[] = "\n$data";
    file_put_contents($path, implode($content));
}

Which does..

$ cat file.txt 
<?php
echo 'Hello world';
?>
$ php test.php 
$ cat file.txt 
<?php
echo 'Hello world';
echo "... again";
?>


回答2:

It's copying each line twice because of your line that says:

 @fwrite($fp, $output);

You're just reading the file to find the end tag, there's no need to write the line you've read as you read.



回答3:

I would add a new <? YOUR CODE ?> after the last line...

Or if you have the new PHP code to add in $code this could be done with a regular expression

$output = preg_replace('\?>','?>'.$code,$output)