0

I have this text-file:

STATIONS_ID;MESS_DATUM;  QN;PP_10;TT_10;TM5_10;RF_10;TD_10;eor
   5371;201912250000;    2;  903.5;   2.3;   2.2; 100.0;   2.3;eor
   [...]
   5371;201912251820;    2;  913.3;   0.4;   0.3; 100.0;   0.4;eor

And I want to get ONLY the last line with timestamp 25-12-2019 18:20 (201912251820).

Thats my php code (finally I want to save the data in my MySQL database):

$row = 1;
if(($handle = fopen("produkt_zehn_now_tu_20191225_20191226_05371.txt", "r")) !== FALSE) 
{
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) 
    {
        echo "<p> 1 fields in line $row: <br /></p>\n";
        $row++;

        for($c=0; $c < 1; $c++) 
        {
            echo $data[$c] . "<br />\n";

            $daten = $data[$c];
            $carray = explode(";", $daten);
            list($station,$zeit,$quali,$luftdruck,$temp2m,$temp5cm,$feuchte,$taupunkt) = $carray;

            echo "<b>temp2m:".$temp2m."</b>";

            /*
            $res_wetterdaten_dwd = $sql_datenbank -> query("INSERT INTO wetterdaten_dwd 
            (daten_zeit, daten_luftdruck, daten_temp2m, daten_temp5cm, daten_feuchte, daten_taupunkt, daten_station)
            VALUES ('".$zeit."', ".$luftdruck.", ".$temp2m.", ".$temp5cm.", ".$feuchte.", ".$taupunkt.", ".$station.")");
            */
        }
    }
    fclose($handle);
}
Freddy
  • 1
  • 3
  • https://stackoverflow.com/questions/3686177/php-to-search-within-txt-file-and-echo-the-whole-line –  Dec 25 '19 at 23:43
  • thanks, but I don't want to search in my text file. I try to get the whole last line. – Freddy Dec 26 '19 at 08:37
  • Find the specific thing in the last line and pick that line. –  Dec 26 '19 at 09:48

1 Answers1

0
    <?php
function getDateFromFile($file = 'text.txt')
{
    $f = fopen($file, 'r');

    $cursor = -1;
    $line = '';
    fseek($f, $cursor, SEEK_END);
    $char = fgetc($f);

    /**
     * Trim trailing newline chars of the file
     */
    while ($char === "\n" || $char === "\r") {
        fseek($f, $cursor--, SEEK_END);
        $char = fgetc($f);
    }

    /**
     * Read until the start of file or first newline char
     */
    while ($char !== false && $char !== "\n" && $char !== "\r") {
        /**
         * Prepend the new char
         */
        $line = $char . $line;
        fseek($f, $cursor--, SEEK_END);
        $char = fgetc($f);
    }

    $value = explode(";", $line);

    $year = substr($value[1], 0, 4);
    $month = substr($value[1], 4, 2);
    $day = substr($value[1], 6, 2);
    $hour = substr($value[1], 8, 2);
    $min = substr($value[1], 10, 2);

    $date = new DateTime("$year-$month-$day $hour:$min");`
    return $date;
}

print_r(getDateFromFile("produkt_zehn_now_tu_20191225_20191226_05371.txt"));