PHP file 按行读取文件内容
作者:互联网
/**
* @param $file //带路径的文件名
* @return false|\Generator|resource
* 读取文件
*/
protected function readFilebyLine($file)
{
$handle = fopen($file, 'rb');
while (feof($handle) === false) {
yield fgets($handle);
}
fclose($handle);
return $handle;
}
/**
* 入口函数
*/
public function handleRun()
{
//遍历文件夹下面所有文件
$dir = Env::get('root_path') . 'public/testlog';
$files = $this->direInfo();
foreach ($files as $value) {
echo 'start_time: ' . date('Y-m-d H:i:s') . PHP_EOL;
//按行读取文件
$fileData = $this->readFilebyLine($dir . '/' . $value);
$baseInfo = [];
foreach ($fileData as $k => $vd) {
//输出文件
var_dump($vd).PHP_EOL;
}
echo 'end_time: ' . date('Y-m-d H:i:s') . PHP_EOL;
break;
}
}
/**
* @return array
* log所有文件名
*/
protected function direInfo()
{
$dir = Env::get('root_path') . 'public/testlog-bak';
$handler = opendir($dir);
while (($filename = readdir($handler)) !== false) {
if ($filename !== "." && $filename !== "..") {
$files[] = $filename;
}
}
closedir($handler);
return $files;
}
/**
* @param $file
* @return false|\Generator|resource
* 读取文件
*/
protected function readFilebyLine($file)
{
//使用yield.对内存没压力
$handle = fopen($file, 'rb');
while (feof($handle) === false) {
yield fgets($handle);
}
fclose($handle);
return $handle;
}
标签:handle,files,return,filename,按行,file,false,PHP 来源: https://www.cnblogs.com/guoshuai-yangxu/p/16350732.html