我已经从气象站txt文件(“realtime.txt”)包含数据。该值由空格分开,如下所示:
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 ...
我想检索这些值的每一个,并将其分配给一个变量,需要一个PHP脚本时要呼应。使用相同的顺序这些变量将是这样的:
$udate $utime $temp $hum $dew $wspeed $wlatest $bearing $rrate $rfall $press $currentwdir $ptrend $ttrend ...
随着我begginner的PHP知识我设法与我肯定会做任何PHP专家的笑容,但...它的工作,如果一个非常奇怪的解决方案做... :-)如果字符数不改变!如果,例如,从11.9ºC温度变化9.5ºC一切都被搞砸了,因为有一个字符计数少的时候!
<?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.'°C<br>';
// ...
谁能教我怎么做一个PHP专家会做的方式吗?提前致谢!
通过它的外观你可以爆炸的空间和使用列表()来设置阵列的每个变量。
list($udate, $utime, $temp, $hum, $dew, $wspeed, $wlatest, $bearing, $rrate, $rfall, $press, $currentwdir, $ptrend, $ttrend) = explode(" ", file_get_contents('realtime.txt'));
在列表中的参数的顺序应该匹配什么样的顺序值是在文件中。
一种替代的方法是保持阵列的阵列,但提出的是结合的。
$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
这意味着你可以通过值环,并使用一个单一的代码行输出的所有值。
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
正如你可以看到你所设置的为$按键阵列中的名称所显示的内容。 所以,如果你设置为“更新日期”作为关键,你会得到一个更好的输出。