<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Weather extends Controller
{
public function tq(){
return $this->fetch('weather');
}
//post 抓取函数
function curlRequest($url,$data = ''){
$ch = curl_init();
$params[CURLOPT_URL] = $url; //请求url地址
$params[CURLOPT_HEADER] = false; //是否返回响应头信息
$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
$params[CURLOPT_TIMEOUT] = 30; //超时时间
if(!empty($data)){
$params[CURLOPT_POST] = true;
$params[CURLOPT_POSTFIELDS] = $data;
}
$params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案
$params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文
curl_setopt_array($ch, $params); //传入curl参数
$content = curl_exec($ch); //执行
curl_close($ch); //关闭连接
return $content;
}
//天气
public function weathers(){
$tq=$_POST['tq'];
// $tp= isset($_POST['tq'])?$_POST['tq']:'';
if(empty($tq)){
//$this->error('请选择城市','/index/Weather/tq');
$this->redirect('/index/Weather/tq');
}
$url="https://www.sojson.com/open/api/weather/json.shtml?city=$tq";
$data= $this->curlRequest($url);
$arr= json_decode($data,true);
dump($arr);
return $this->fetch('weather',['arr'=>$arr]);
城市: {$arr['city']}
最高温度 {$arr['data']['forecast']['0']['high']}
最低温度{$arr['data']['forecast']['0']['low']}
温馨提示{$arr['data']['forecast']['0']['notice']} {/if}
namespace app\index\controller;
use think\Controller;
use think\Request;
class Weather extends Controller
{
public function tq(){
return $this->fetch('weather');
}
//post 抓取函数
function curlRequest($url,$data = ''){
$ch = curl_init();
$params[CURLOPT_URL] = $url; //请求url地址
$params[CURLOPT_HEADER] = false; //是否返回响应头信息
$params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
$params[CURLOPT_FOLLOWLOCATION] = true; //是否重定向
$params[CURLOPT_TIMEOUT] = 30; //超时时间
if(!empty($data)){
$params[CURLOPT_POST] = true;
$params[CURLOPT_POSTFIELDS] = $data;
}
$params[CURLOPT_SSL_VERIFYPEER] = false;//请求https时设置,还有其他解决方案
$params[CURLOPT_SSL_VERIFYHOST] = false;//请求https时,其他方案查看其他博文
curl_setopt_array($ch, $params); //传入curl参数
$content = curl_exec($ch); //执行
curl_close($ch); //关闭连接
return $content;
}
//天气
public function weathers(){
$tq=$_POST['tq'];
// $tp= isset($_POST['tq'])?$_POST['tq']:'';
if(empty($tq)){
//$this->error('请选择城市','/index/Weather/tq');
$this->redirect('/index/Weather/tq');
}
$url="https://www.sojson.com/open/api/weather/json.shtml?city=$tq";
$data= $this->curlRequest($url);
$arr= json_decode($data,true);
dump($arr);
return $this->fetch('weather',['arr'=>$arr]);
}
HTML界面
城市天气:{if empty($arr)} {else/}
城市: {$arr['city']}
最高温度 {$arr['data']['forecast']['0']['high']}
最低温度{$arr['data']['forecast']['0']['low']}
温馨提示{$arr['data']['forecast']['0']['notice']} {/if}
![](https://i-blog.csdnimg.cn/blog_migrate/65546733348edfcfecef87ed5bc8c84f.png)