Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
PHP 代码
<?php
define('JUHE_API','http://apis.juhe.cn/simpleWeather/query');
define('JUHE_KEY','abc4b64ae7656b460723402175a5650b');
function getTianqi(string $city,$isget=1){
$data = ['key'=> JUHE_KEY,'city'=>$city];
$url = JUHE_API.'?';
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,JUHE_API);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_AUTOREFERER,1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
if ($isget) {
foreach ($data as $k => $v) {
$url .= $k.'='.$v.'&';
}
curl_setopt($ch,CURLOPT_URL,$url);
} else {
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
}
$rs = curl_exec($ch);
curl_close($ch);
return json_decode($rs,true);
}
$arrs = getTianqi(isset($_POST['city'])?$_POST['city']:'北京',0);
$errorMessage='';
if ($arrs['error_code'] == 0) {
$city = $arrs['result']['city'];
$real = $arrs['result']['realtime'];
$future = $arrs['result']['future'];
$futureHTML = '<table class="table"><thead class="thead-dark"><tr><th>日期:</th><th>温度</th><th>天气情况</th><th>风向</th></tr><thead/>';
foreach ($future as $f) {
$futureHTML.= "<tr><td>".$f['date']."</td>";
$futureHTML.= "<td>".$f['temperature']."</td>";
$futureHTML.= "<td>".$f['weather']."</td>";
$futureHTML.= "<td>".$f['direct']."</td></tr>";
}
$futureHTML .= '</table>';
} else {
$errorMessage = $arrs['reason'];
}
?>
HTML 代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>天气预报</title>
<link
href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.6.0/css/bootstrap.css"
rel="stylesheet"
/>
<style>
.lead label {
margin-right: 10px;
}
</style>
</head>
<body>
<?=$errorMessage?>
<div
class="jumbotron"
style="display:<?=!empty($errorMessage)?'none':'block'?>;"
>
<h1 class="display-4">当前城市天气:</h1>
<p class="lead">
<label>城市:<?=!empty($city)?$city:'暂无数据'?></label>
<label
>温度:<?=!empty($real['temperature'])?$real['temperature']:''?>℃</label
>
<label>天气:<?=!empty($real['info'])?$real['info']:''?></label>
<label>湿度:<?=!empty($real['humidity'])?$real['humidity']:''?></label>
<label>风向:<?=!empty($real['direct'])?$real['direct']:''?></label>
<label>风力:<?=!empty($real['power'])?$real['power']:''?></label>
<label>空气质量:<?=!empty($real['aqi'])?$real['aqi']:''?></label>
</p>
<hr class="my-4" />
<form action="" method="post" class="input-group">
<input
class="form-control"
type="text"
name="city"
value="<?=$city?>"
placeholder="请输入城市名称"
/>
<button class="btn btn-primary input-group-append" type="submit">
查询天气
</button>
</form>
<hr class="my-4" />
<p>近5天天气情况:</p>
<?=!empty($futureHTML)?$futureHTML:'暂无数据'?>
</div>
</body>
</html>
运行结果: