从最后读取大文件 [英] Reading large files from end

查看:95
本文介绍了从最后读取大文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以从PHP读取文件吗?例如,如果我想读取最后10-20行?

而且,据我所知,如果文件大小超过10mbs我开始得到错误。



如何防止这个错误?



对于读取普通文件,我们使用下面的代码:如果($ handle){
while(($ buffer = fgets($ handle,4096))!== $ false $ $ $ $

$ $ $ $ $ $ $ $ ){
$ i1 ++;
$ content [$ i1] = $ buffer;

if(!feof($ handle)){
echoError:unexpected fgets()fail \\\
;
}
fclose($ handle);
}

我的文件可能会超过10mbs,但我只需要读取最后几个线。如何做到这一点?



谢谢

解决方案

PHP,但常见的解决方案是使用 tac 命令,这是 cat 并反向加载文件。使用exec()或passthru()在服务器上运行它,然后读取结果。用法示例:

 <?php 
$ myfile ='myfile.txt';
$ command =tac $ myfile> /tmp/myfilereversed.txt;
exec($ command);
$ currentRow = 0;
$ numRows = 20; //在此行数之后停止
$ handle = fopen(/ tmp / myfilereversed.txt,r); $(!feof($ handle)&& $ currentRow< = $ numRows){
$ currentRow ++;
$ buffer = fgets($ handle,4096);
echo $ buffer。< br>;
}
fclose($ handle);
?>


Can I read a file in PHP from my end, for example if I want to read last 10-20 lines?

And, as I read, if the size of the file is more than 10mbs I start getting errors.

How can I prevent this error?

For reading a normal file, we use the code :

if ($handle) {
    while (($buffer = fgets($handle, 4096)) !== false) {
    $i1++;
    $content[$i1]=$buffer;
    }
    if (!feof($handle)) {
        echo "Error: unexpected fgets() fail\n";
    }
    fclose($handle);
}

My file might go over 10mbs, but I just need to read the last few lines. How do I do it?

Thanks

解决方案

It's not pure PHP, but the common solution is to use the tac command which is the revert of cat and loads the file in reverse. Use exec() or passthru() to run it on the server and then read the results. Example usage:

<?php
$myfile = 'myfile.txt';
$command = "tac $myfile > /tmp/myfilereversed.txt";
exec($command);
$currentRow = 0;
$numRows = 20;  // stops after this number of rows
$handle = fopen("/tmp/myfilereversed.txt", "r");
while (!feof($handle) && $currentRow <= $numRows) {
   $currentRow++;
   $buffer = fgets($handle, 4096);
   echo $buffer."<br>";
}
fclose($handle);
?>

这篇关于从最后读取大文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆