Skip to content
PHP Logo

Are there any specific PHP functions or libraries that can help with splitting log files by date?

To split log files by date in PHP, you can use the `fopen`, `fread`, and `fwrite` functions to read the log file line by line, extract the date from each log entry, and then write the log entry to a new file based on the date. You can also use the `DateTime` class to parse and format the dates.

php
$logFile = 'example.log';
$handle = fopen($logFile, "r");

while (($line = fgets($handle)) !== false) {
    $date = DateTime::createFromFormat('Y-m-d H:i:s', substr($line, 0, 19));
    $outputFile = $date->format('Y-m-d') . '_log.log';
    
    $outputHandle = fopen($outputFile, "a");
    fwrite($outputHandle, $line);
    fclose($outputHandle);
}

fclose($handle);