使用PHP从文本文件的最后一行提取数据


Extract data from last line in a text file using PHP

我正试图从文本文件的最后一行提取特定的数据,以便能够单独显示。例如,我想从以下文件中提取降雨量数据:

#date #time  #blah #rainfall  #blah   #blah
200813 1234   1234    0.5      1234    1234
200813 1235   1234    1.2      1234    1234
200813 1236   1234    3.5      1234    1234
200813 1237   1234    0.2      1234    1234
200813 1238   1234    0.1      1234    1234

我想在网页上以这种方式使用数据:

目前预测降雨量:0.1毫米

所以我只需要最后一行的0.1。由于文件是远程的,并且在文件底部添加了新行,所以我只需要最后一行。

有人能帮忙吗?我已经为此绞尽脑汁好几天了。

$file = file('path/to/file');
$lastLine = end($file);

应该做你需要做的事。

或者,如果你是一句俏皮话的粉丝:-

$lastLine = end(file('path/to/file'));

这将输出您的预期降雨量,假设您的文件名为"data.txt":-

printf('Rainfall expected %smm', array_values(array_filter(explode(' ', end(file('data.txt')))))[3]);

请参阅file()和end()

如果文件不是太大或接近一行,通常使用一行完成:

vprintf(
    'Rainfall prediced now: %4$smm'
    , explode(' ', end((
        file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)
    )))
);

如果输入格式更复杂,也可以使用sscanfpreg_match来解析最后一行。

编辑当您编写文件时,文件很小,您也可以将其加载到字符串(file_get_contents)中,并从后面解析该字符串:

$buffer = '#date #time  #blah #rainfall  #blah   #blah
200813 1234   1234    0.5      1234    1234
200813 1235   1234    1.2      1234    1234
200813 1236   1234    3.5      1234    1234
200813 1237   1234    0.2      1234    1234
200813 1238   1234    0.1      1234    1234';
preg_match('/([^ ]+)'s+'d+'s+'d+'R?$/', $buffer, $matches)
    && vprintf('Rainfall prediced now: %2$smm', $matches);
// prints "Rainfall prediced now: 0.1mm"

如果您使用的是基于Unix的系统,请考虑使用tail命令。

$file = escapeshellarg($file); 
$line = `tail -n 1 $file`;

以下也将起作用:

$fp = fopen('file.txt', 'r');
$pos = -1; $line = ''; $c = '';
do {
    $line = $c . $line;
    fseek($fp, $pos--, SEEK_END);
    $c = fgetc($fp);
} while ($c != PHP_EOL);
echo $line; //last line
fclose($fp); 

如前所述,这不会将整个文件加载到内存中,而且速度很快。

希望这能有所帮助!