php文件操作技巧FileSystem

1.获取目前下的子目录(目录下的所有同级文件包括文件夹)
php代码

$path = '/data/logs';
$dirChirdenList = scandir($path);
var_dump($dirChirdenList);

输出

array(28) {
  [0] => string(1) "."
  [1] => string(2) ".."
  [2] => string(8) "activity"
  [3] => string(5) "admin"
  [4] => string(4) "auth"
  [5] => string(13) "codeexception"
  [6] => string(6) "coobar"
  [7] => string(16) "coobar_error_log"
  [8] => string(4) "cron"
  [9] => string(9) "http_api6"
  [10] => string(13) "http_service6"
  [11] => string(8) "http_sso"
  [12] => string(5) "nginx"
  [13] => string(3) "pay"
  ....
  ...
}

php代码

$handler = opendir('/data/logs');
$files = [];
while( ($filename = readdir($handler)) !== false ) {
  $files[] = $filename;
}
closedir($handler);
var_dump($files);

输出

array(28) {
  [0] => string(6) "wallet"
  [1] => string(13) "codeexception"
  [2] => string(19) "php-fpm54.error.log"
  [3] => string(15) "php54.error.log"
  [4] => string(17) "php-fpm.error.log"
  [5] => string(7) "upgrade"
  [6] => string(18) "php-fpm54.slow.log"
  [7] => string(4) "auth"
  [8] => string(8) "activity"
  [9] => string(16) "coobar_error_log"
  [10] => string(13) "http_service6"
  [11] => string(3) "sql"
  [12] => string(1) "."
  [13] => string(6) "rsyncd"
  ...
  ...
}

递归获取该文件下所有文件

$dir = "/databackup/php18/logs/codeexception";
$fileList = [];
$result = getDirFile($dir,$fileList);
function getDirFile($dir,&$fileList)
{
    $handler = opendir($dir);
    while (($filename = readdir($handler)) !== false) {
        if ($filename == '.' || $filename == '..') {
            continue;
        }
        if (is_dir($dir . "/" . $filename)) {
            getDirFile($dir . "/" . $filename,$fileList);
        } else {
            $fileList[] = $dir . "/" . $filename;
        }
    }
    closedir($handler);
    return true;
}

2.将日志文件变成一个数组 每一行一个key (不推荐打开大文件内容 容易内存溢出)
文件内容

row1
row2
row3
row4
row5
row6

php代码

$rows = file('/home/hls/test/test.log);
var_dump($rows);

输出

array(6) {
  [0] => string(5) "row1
"
  [1] => string(5) "row2
"
  [2] => string(5) "row3
"
  [3] => string(5) "row4
"
  [4] => string(5) "row5
"
  [5] => string(5) "row6
"
}

3.逐行读取文件内容(适合大文件 文件分析)

文件内容

row1
row2
row3
row4
row5
row6

php代码

$handler = fopen('/home/hls/test/test.log','r');
$rows = [];
while (!feof($handler)) {
  $row = fgets($handler);
  if ($row !== false) {
     $rows[] = $row;
  }
}
fclose($handler);
dump($rows);exit;

输出

array(6) {
  [0] => string(5) "row1
"
  [1] => string(5) "row2
"
  [2] => string(5) "row3
"
  [3] => string(5) "row4
"
  [4] => string(5) "row5
"
  [5] => string(5) "row6
"
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值