PHP:从txt文件中获取单个值

我有这个文本文件:


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

我只想得到时间戳为 25-12-2019 18:20 (201912251820) 的最后一行。


这就是我的 php 代码(最后我想将数据保存在我的 MySQL 数据库中):


$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);

}


斯蒂芬大帝
浏览 119回答 1
1回答

函数式编程

&nbsp; &nbsp; <?phpfunction getDateFromFile($file = 'text.txt'){&nbsp; &nbsp; $f = fopen($file, 'r');&nbsp; &nbsp; $cursor = -1;&nbsp; &nbsp; $line = '';&nbsp; &nbsp; fseek($f, $cursor, SEEK_END);&nbsp; &nbsp; $char = fgetc($f);&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Trim trailing newline chars of the file&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; while ($char === "\n" || $char === "\r") {&nbsp; &nbsp; &nbsp; &nbsp; fseek($f, $cursor--, SEEK_END);&nbsp; &nbsp; &nbsp; &nbsp; $char = fgetc($f);&nbsp; &nbsp; }&nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp;* Read until the start of file or first newline char&nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; while ($char !== false && $char !== "\n" && $char !== "\r") {&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Prepend the new char&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;*/&nbsp; &nbsp; &nbsp; &nbsp; $line = $char . $line;&nbsp; &nbsp; &nbsp; &nbsp; fseek($f, $cursor--, SEEK_END);&nbsp; &nbsp; &nbsp; &nbsp; $char = fgetc($f);&nbsp; &nbsp; }&nbsp; &nbsp; $value = explode(";", $line);&nbsp; &nbsp; $year = substr($value[1], 0, 4);&nbsp; &nbsp; $month = substr($value[1], 4, 2);&nbsp; &nbsp; $day = substr($value[1], 6, 2);&nbsp; &nbsp; $hour = substr($value[1], 8, 2);&nbsp; &nbsp; $min = substr($value[1], 10, 2);&nbsp; &nbsp; $date = new DateTime("$year-$month-$day $hour:$min");`&nbsp; &nbsp; return $date;}print_r(getDateFromFile("produkt_zehn_now_tu_20191225_20191226_05371.txt"));
打开App,查看更多内容
随时随地看视频慕课网APP