Cyrus
Cyrus

Reputation: 7

php - output last block of text(separated by empty lines) from a text file

I have a large text file in this form:

This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.

This is a linie of text.
This is a linie of text.

This is a linie of text.
This is a linie of text.
This is a linie of text.

etc. I want to output the last couple of chunks/blocks of text from this file in my website. I currently use this:

$line = '';

$f = fopen('output.log', 'r');
$cursor = -1;

fseek($f, $cursor, SEEK_END);
$char = fgetc($f);

/**
 * Trim trailing newline chars of the file
 */
while ($char === "\n" || $char === "\r") {
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}

/**
 * Read until the start of file or first newline char
 */
while ($char !== false && $char !== "\n" && $char !== "\r") {
    /**
     * Prepend the new char
     */
    $line = $char . $line;
    fseek($f, $cursor--, SEEK_END);
    $char = fgetc($f);
}

echo $line;

That shows just the last line. Any thought about this would be awesome! Thanks! Edit: All blocks are separated by empty lines, the script should print the last few blocks.

Upvotes: 0

Views: 365

Answers (4)

Sergiu Galkin
Sergiu Galkin

Reputation: 41

For large files this code will work faster than regular expressions .

$mystring = file_get_contents('your/file');    
$pos = strrpos($mystring, "\n")
if($pos === false)
    $pos = strrpos($mystring, "\r");
$result = substr($mystring, $pos);

Upvotes: 0

Tim
Tim

Reputation: 8616

unless the file is prohibitively large, you could just explode it

$allLines = explode("\n", file_get_contents('your/file') );
$endLines = array_slice( $allLines, -2 );
echo implode("\n", $endLines );

If you want to match blocks containing any number of lines, you could explode with a double line break "\n\n"

If the whitespace characters aren't reliably uniform, you could use preg_match. e.g.

$allBlocks = preg_split( '/[\n\r]\s*[\n\r]/', file_get_contents('your/file'), -1, PREG_SPLIT_NO_EMPTY );

Upvotes: 1

Phil Cross
Phil Cross

Reputation: 9302

Here go:

file.txt

This is a linie of text.
This is a linie of text.
This is a linie of text.
This is a linie of text.

This is a linie of text.
This is a linie of text.

This is a linie of text.
This is a linie of text.
This is a linie of text.

process.php:

$fileContents = file('file.txt', FILE_SKIP_EMPTY_LINES);
$numberOfLines = count($fileContents);

for($i = $numberOfLines-2; $i<$numberOfLines; $i++)
{
    echo $fileContents[$i];
}

This will output the last 2 lines of text from the file

Alternatively, use substr to return the last 50 letters of text:

$fileContents = file_get_contents('file.txt');
echo subtr($fileContents, -50, 50);

Upvotes: 0

silkfire
silkfire

Reputation: 25965

Read in the file with file_get_contents() and the explode by double new line, then pick out the last element with array_pop().

Upvotes: 0

Related Questions