php导入显示文件太大,PHP 读取大文件并显示的简单实例(推荐)

使用PHP读取日志文件,当文件比较大的时候,会报内存不足,因此应该部分读取,读取指定的行数的数据

c6519c8bedbb101345d42111a92cf5b3.png

PHP代码:

class Test{

//日志路径

const LOG_PATH="E:\phpServer\Apache\logs\error.log";

const NGINX_LOG_PATH="E:\phpServer\\nginx\logs\error.log";

//显示的行数

const PAGES=50;

public static function main(){

header("content-type:text/html;charset=utf-8");

if(!empty($_GET['action'])){

self::$_GET['action']();

exit;

}

}

public static function showApacheLogs(){

$test=new Test();

$result=$test->readLogs(self::LOG_PATH,self::PAGES);

$html="";

foreach($result as $line){

if(strpos($line,"error:")){

$line="".$line."";

}

$html.="

".$line."
";

}

echo $html;

}

public static function showNginxLogs(){

$test=new Test();

$result=$test->readLogs(self::NGINX_LOG_PATH,self::PAGES);

$html="";

foreach($result as $line){

if(strpos($line,"error")){

$line="".$line."";

}

$html.="

".$line."
";

}

echo $html;

}

/**

* 读取日志

*/

private function readLogs($filePath,$num=20){

$fp = fopen($filePath,"r");

$pos = -2;

$eof = "";

$head = false; //当总行数小于Num时,判断是否到第一行了

$lines = array();

while($num>0){

while($eof != "\n"){

if(fseek($fp, $pos, SEEK_END)==0){ //fseek成功返回0,失败返回-1

$eof = fgetc($fp);

$pos--;

}else{ //当到达第一行,行首时,设置$pos失败

fseek($fp,0,SEEK_SET);

$head = true; //到达文件头部,开关打开

break;

}

}

array_unshift($lines,fgets($fp));

if($head){ break; } //这一句,只能放上一句后,因为到文件头后,把第一行读取出来再跳出整个循环

$eof = "";

$num--;

}

fclose($fp);

return array_reverse($lines);

}

}

Test::main();

?>

*{

padding: 0;

margin: 0;

}

.logsBox{

margin:5px;

padding: 5px;

width: 600px;

background: #000;

color:#fff;

font-size: 13px;

float: left;

}

.logsBox .line{

margin: 12px 0;

}

日志读取...
日志读取...

$(function(){

function showLogs(api,showClass){

function readLogs(){

$.ajax({

url:api,

type:"get",

dataType:"text",

success:function(data){

$(showClass).html(data);

}

});

}

readLogs();

setInterval(readLogs,5000);

}

showLogs("?action=showNginxLogs",".nginx");

showLogs("?action=showApacheLogs",".apache");

});

以上这篇PHP 读取大文件并显示的简单实例(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值