我有一个curl脚本,可以从服务器获取json数据。当我将数据保存到文件中时,它可以正常工作,并且仅在有新值可用时才检索数据。
但是,如果我插入一个INSERT查询以将值保存到数据库中,它将开始在循环中获取冗余值。就像每2分钟就会有新数据一样,当我将数据保存到文件中时,它只会每2分钟获取一次新数据。但是我用文件数据插入代码替换了查询,它开始循环并获取冗余数据,大约每5秒一次。
我该如何更正脚本,以便在有更新的脚本时可以获取数据。就像我将数据保存到文件中一样。
这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="300">
<title>Weather Data</title>
<meta charset="utf-8">
</head>
<body>
<h2>Connect.php</h2>
<div>
<?php
require("Connection.php");
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://cors.io/?http://api.xxxxx.com/live/xxxxxxxxxx=m/s",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
//CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"Cache-Control: no-cache"
),
));
$response = curl_exec($curl);
$Wdata = json_decode($response, true);
$tem = $Wdata["temperature"];
$tem2 = $Wdata["2nd_temp"];
$hum = $Wdata["humidity"];
$tim = $Wdata["dateTime"];
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
echo "<br>";
echo "temp1:".$tem;
echo "<br>";
echo "humidity:".$hum;
echo "<br>";
echo "time:".$tim;
echo "<br>";
if ( $fl = fopen('weatherData.json','a'))
{ fwrite($fl,"\"Weather Data\": { \"Time\" : \"". $tim . "\" ,"."\"Humidity\" : \"". $hum . "\"}\n" );
//echo $_id.';'.$_time;
fclose($fl); }
// Here code to save $response into database; When I un-comment it, the script starts fetching redundant data in a loop
/*
try{
$sql = "INSERT INTO weatherdata (datetime, temperature, humidity)
VALUES ('".$tim."','".$tem."','".$hum."')";
echo "<meta http-equiv='refresh' content='0'>";
($conn->query($sql));
//$conn = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
*/
}
?>
</div>
</body>
</html>