PHP言語 直接file関数で大きなファイルを操作する方法

サンプルコード:

$fp = fopen($file, “r");
$num = 10;
$chunk = 4096;
$fs = sprintf(“%u", filesize($file));
$max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);
for ($len = 0; $len < $max; $len += $chunk) {
$seekSize = ($max – $len &gt; $chunk) ? $chunk : $max – $len;
fseek($fp, ($len + $seekSize) * -1, SEEK_END);
$readData = fread($fp, $seekSize) . $readData;
if (substr_count($readData, “\n") &gt;= $num + 1) {
preg_match(“!(.*?\n){“.($num)."}$!", $readData, $match);
$data = $match[0];
break;
}
}
fclose($fp);
echo $data;

Development

Posted by arkgame