PHP count text file rows based on date and time

PHP count text file rows based on date and time

php get first row of csv file
php read file line by line
php read csv file
php file
php read file into array
php loop through csv
php file handler
php file stream

I have log data on text file (.txt)

The data on text file like this:

City Siren FCT_Tester #1 10039273
Date: 160518, Version: 1.00             

ID  Test                                                Min Max Unit
1   Battery level                           2.85    3.40    V
2   Piezo sound level                           1.45    2.80    V   
3   Left D3  (Ch 3) light intensity                                 2000     
10000   mcd
4   Right D2  (Ch 1) light intensity                            2000     
10000   mcd

Date    Time    Battery level                           Piezo sound level                            
Left D3  (Ch 3) light intensity                                 Right D2  
(Ch 1) light intensity                          

Wed, Sep 19  2018   06:47:01    3.372   1.621   9117.000    7303.300
Wed, Sep 19  2018   06:47:19    3.374   1.614   8614.400    7152.300
Wed, Sep 19  2018   08:08:04    3.378   1.604   9586.500    7422.400
Wed, Sep 19  2018   08:08:20    3.375   1.632   9249.300    6682.200
Wed, Sep 19  2018   08:08:44    3.377   1.615   9059.700    6777.100
Wed, Sep 19  2018   08:09:15    3.376   1.626   8902.500    6962.200

What I've done is:

echo count(file($files));

It will get the all rows.

So my question now, I want to count the rows of text file with condition from date and time. Get the count Wed, Sep 19 2018 08:00:00 until Wed, Sep 19 2018 11:00:00

So the result should be: 4

Is it possible?

UPDATE The log file is using tab, then the code can' read with error:

Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string

below is the log file

Tue, Sep 18  2018   23:59:53    3.380   1.622   9958.500    7301.000
Wed, Sep 19  2018   00:00:08    3.380   1.622   8817.900    7194.800
Wed, Sep 19  2018   00:00:28    3.343   1.598   9089.500    7033.800
Wed, Sep 19  2018   00:00:45    3.376   1.602   8789.200    7285.200
Wed, Sep 19  2018   00:01:01    3.376   1.629   8406.000    7295.700
Wed, Sep 19  2018   00:01:17    3.378   1.623   8468.100    7382.800
Wed, Sep 19  2018   00:01:36    3.366   1.619   9462.900    7200.600
Wed, Sep 19  2018   00:01:54    3.370   1.622   9389.700    7018.500
Wed, Sep 19  2018   00:02:21    3.375   1.582   9637.100    7347.500
Wed, Sep 19  2018   00:02:36    3.377   1.595   8775.200    7414.700
Wed, Sep 19  2018   00:02:52    3.340   1.585   8955.300    7376.700
Wed, Sep 19  2018   00:03:20    3.263   1.600   8325.900    6694.700
Wed, Sep 19  2018   00:03:37    3.369   1.616   9554.400    7045.700

You don't have to do any special splitting or regexing. Just use DateTime::createFromFormat and specify your format.

If your file is formated like Tue,<space>Sep<space>18<tab>2018<tab>23:59:53<tab>[...] you can use the following format ???,?M?d?Y?H:i:s+ which expands to

  1. ??? - Ignore first 3 characters (wed, mon, etc)
  2. , - An comma
  3. ? - Some character (space, tab, any)
  4. M - The month as text (Sep, Sept, September, etc)
  5. ? - Some character (space, tab, any)
  6. d - The day as number
  7. ? - Some character (space, tab, any)
  8. Y - The year as four digits (2008, 2009, etc)
  9. ? - Some character (space, tab, any)
  10. Y - The hours as digits in 24h (09, 10, 13, etc)
  11. : - An :
  12. i - The minutes as digits (09, 10, 13, etc)
  13. : - An :
  14. s - The seconds as digits (09, 10, 13, etc)
  15. + - Ignore (but warn!) any trailing characters

So your code could look like

//Set Time-Span
$fromDateTime = new DateTime('Wed, Sep 19  2018 00:01:00');
$toDateTime = new DateTime('Wed, Sep 19  2018 00:02:00');

// Load File
$file = file_get_contents('log.txt');

// Split by lines
$lines = explode("\n",$file);

// counter
$rowsintimespan = 0;

// Do Line-By-Line starting by Line 16 (Array Index 15)
for($i = 15; $i < count($lines); $i++) {
    // if the file is "Tue,<space>Sep<space>18<tab>2018<tab>23:59:53<tab>"
    $dateobj = DateTime::createFromFormat("???,?M?d?Y?H:i:s+", $lines[$i]);

    // check if date is in your Timespan
    if($dateobj < $toDateTime && $dateobj > $fromDateTime) {
        $rowsintimespan++; // count if in timespan
    }
}

// Debug-Output
echo $rowsintimespan;

Edit to reply to your comment providing the real file:

By looking at a hexdump -C of your test.txt you can find, that there are two spaces between day and year (last 20 20 in the first line).

00000270  0a 0d 0a 54 75 65 2c 20  53 65 70 20 31 38 20 20  |...Tue, Sep 18  |
00000280  32 30 31 38 09 32 33 3a  35 39 3a 35 33 09 33 2e  |2018.23:59:53.3.|
00000290  33 38 30 09 31 2e 36 32  32 09 39 39 35 38 2e 35  |380.1.622.9958.5|
000002a0  30 30 09 37 33 30 31 2e  30 30 30 0d 0a 57 65 64  |00.7301.000..Wed|

So your format would be ???,?M?d??Y?H:i:s+. Notice the second ? between d??Y.

PHP count line/row on text file based on value column, PHP count line/row on text file based on value column 19 2018 08:00:00'); $​toDateTime = new DateTime('Wed, Sep 19 2018 19:59:00'); $file  Counts the number of words inside string.If the optional format is not specified, then the return value will be an integer representing the number of words found. . In the event the format is specified, the return value will be an array, content of which is dependent on the form


I'm not regex expert but you can try this one:

<?php

$content = file_get_contents('b.txt');

$lines = preg_match_all('/(Mon|Tue|Wed|Thu|Fri|Sat|Sun),[ ]{1,}(Jun|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[ ]{1,}[0-9]{2,2}.*/m', $content, $matches);
$fromDateTime = new DateTime('Wed, Sep 19  2018 08:00:00');
$toDateTime = new DateTime('Wed, Sep 19  2018 11:00:00');

foreach($matches[0] as  $line){
    $cols = explode(' ', $line);
    $dateTimeArray = [];
    foreach ($cols as $index => $col) {
        if ($index < 8 && $col) {
            $dateTimeArray[] = $col;
        }
    }
    $dateTime = new DateTime(implode(' ', $dateTimeArray));
    if ($dateTime > $fromDateTime && $dateTime < $toDateTime) {
        print_r($line."\n");
    }   
}

PHP Solutions: Dynamic Web Design Made Easy, 160 moving temporary file to upload folder, 160 not using in double-quoted string, PHP, 106 using with for loop, 185 COUNT() function, MySQL counting records in 96–98 using PHP to identify, 96–103 custom-built PHP functions locating updating records, 360–371 using phpMyAdmin to create, 291 date and time  The count () function returns the number of elements in an array. count ( array, mode ) Parameter Values. Required. Specifies the array. Optional. Specifies the mode. Possible values: 0 - Default. Does not count all elements of multidimensional arrays. 1 - Counts the array recursively (counts all the elements of multidimensional arrays)


I don't know what do you want exactly but for getting a text file line by line his is he code in which you can parse the lines for special text.

<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
$counter=0;
 while(!feof($file))
  {
  echo fgets($file). "<br>";
  $counter++;
 }
fclose($file);
?>

file - Manual, Note: You can use file_get_contents() to return the contents of a file as a string. computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. To write all the lines of the file in other words to read the file line by line you can write the code like this: echo count($names). file: Required. Specifies the open file to return a line from: length: Optional. Specifies the number of bytes to read. Reading stops when length-1 bytes have been reached, or when a new line occurs, or on EOF. If no length is specified, it reads until end of the line


fgetcsv - Manual, fgetcsv — Gets line from file pointer and parse for CSV fields the auto_detect_line_endings run-time configuration option may help resolve the problem. 7.4.0, The escape parameter now also accepts an empty string to disable the $num = count($data); echo "<p> $num fields in line $row: <br /></p​>\n"; $row++; If omitted, the current date and time will be used (as in the examples above). The PHP mktime() function returns the Unix timestamp for a date. The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified. Syntax


440+ Common PHP Terms & Syntax (Quick Review Facts), matching a specified pattern Formats a GMT/UTC date/time Returns the Unix timestamp Outputs a file with the PHP syntax highlighted 244. can abort the running of a script Returns a string from the elements of an array Checks if a French Republican date Converts a Julian day count to a Gregorian date Converts a  The count_chars () function returns information about characters used in a string (for example, how many times an ASCII character occurs in a string, or which characters that have been used or not been used in a string). count_chars ( string,mode ) Parameter Values. Required. The string to be checked. Optional. Specifies the return modes. 0 is


substr_count - Manual, substr_count() returns the number of times the needle substring occurs in the haystack string. If the offset is negative, counting starts from the end of the string. In this chapter we will teach you how to open, read, and close a file on the server. A better method to open files is with the fopen () function. This function gives you more options than the readfile () function. We will use the text file, "webdictionary.txt", during the lessons: The first parameter of fopen () contains the name of the file to