MeteoCaldas
MeteoCaldas

Reputation: 27

Retrieve data inside txt file to use it php script

I have a txt file ('realtime.txt') containing data from a weather station. The values are separated by a blank space and look like this:

02/02/19 11:50:10 11.1 60 3.6 23.6 19.4 338 0.0 1.5 1021.4 NNW +0.3 -1.4 ... 

I would like to retrive each one of these values and assing it to a variable, to be echoed when needed in a php script. Using the same order those variables would be something like this:

$udate $utime $temp $hum $dew $wspeed $wlatest $bearing $rrate $rfall $press $currentwdir $ptrend $ttrend ... 

With my begginner's php knowledge I managed to do it with a very odd solution that I am sure will make any php expert smile but... it's working if... :-) if number of characters doesn't change!!! If for instance, temperature changes from 11.9ºC to 9.5ºC everything gets messed up because there is one character less when counting!

<?php 

// starting from caracter n read following i bytes
$udate = file_get_contents('realtime.txt', FALSE, NULL, 0, 8); 
$utime = file_get_contents('realtime.txt', FALSE, NULL, 9, 8); 
$temp = file_get_contents('realtime.txt', FALSE, NULL, 18, 4); 

// ...

echo 'updated @: '.$udate.' '.$utime.'<br>'; 
echo 'temperature is: '.$temp.'&deg;C<br>'; 

// ... 

Could anyone please teach me how to do this the way a php expert would do? Thanks in advance!

Upvotes: 0

Views: 135

Answers (1)

Andreas
Andreas

Reputation: 23968

By the looks of it you can just explode on space and use list() to set the array to each variable.

list($udate, $utime, $temp, $hum, $dew, $wspeed, $wlatest, $bearing, $rrate, $rfall, $press, $currentwdir, $ptrend, $ttrend) = explode(" ", file_get_contents('realtime.txt'));

The order of the parameters in list should match what order the values are in the file.


An alternative method is to keep the array as an array but make is associative.

$keys = ['udate', 'utime', 'temp', 'hum', 'dew', 'wspeed', 'wlatest', 'bearing', 'rrate', 'rfall', 'press', 'currentwdir', 'ptrend', 'ttrend'];
$arr = array_combine($keys, explode(" ", file_get_contents('realtime.txt')));

echo $arr['udate']; //02/02/19

This means you can loop through the values and use a single line of code to output all values.

foreach($arr as $key => $val){
    echo $key . " is " . $val;
}
// udate is 02/02/19
// utime is 11:50:10
// temp is 11.1
// And so on

As you can see what you set the as the name in the $keys array is what is displayed.
So if you set "Date updated" as key you will get a nicer output.

Upvotes: 3

Related Questions