批改状态:合格
老师批语:代码附上实例图片会更加直观
$yan = '0123456789abcdefghijklmnopqrstuvwsyz';$code1 = mt_rand(0,strlen($yan)-1);$code2 = mt_rand(0,strlen($yan)-1);$code3 = mt_rand(0,strlen($yan)-1);$code4 = mt_rand(0,strlen($yan)-1);//验证码echo $yan[$code1].$yan[$code2].$yan[$code3].$yan[$code4];//加入颜色echo '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.$yan[$code1].'</span>'.'<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.$yan[$code2].'</span>'.'<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.$yan[$code3].'</span>'.'<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.$yan[$code4].'</span>';echo '<br>';//循环方式加入颜色for($i=0;$i<4;$i++){echo '<span style="color:rgb('.mt_rand(0,255).','.mt_rand(0,255).','.mt_rand(0,255).')">'.$yan[mt_rand(0,strlen($yan)-1)].'</span>';}
$data=['key'=>'这里填接口的key','city'=>'地点'];$ch=curl_init();//创建curl连接curl_setopt($ch,CURLOPT_URL,'http://apis.juhe.cn/simpleWeather/query');curl_setopt($ch,CURLOPT_POST,1);//用POST方式,1为true。curl_setopt($ch,CURLOPT_POSTFIELDS,$data);//用POST发送接口数据curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// 要求结果保存到字符串中还是输出到屏幕上$html = curl_exec($ch);//执行curl输出到页面上,如果写在curl_close($ch)关闭后,就不能输出页面上。curl_close($ch);//关闭curl连接$html=json_decode($html,true);//关闭json数据,把json数据转换成数组格式赋值给变量;//print_r($html);//天气预报数组数据echo $html['result']['future']['1']['weather'];//单个数据输出
function get_url($url,$data,$is_post=0){$ch = curl_init(); // 创建一个curl,一直存在,所以在最后要关闭.// curl_setopt($ch, CURLOPT_URL ,'http://apis.juhe.cn/simpleWeather/query?key=b4bae7656b473402175550b&city=合肥');if($is_post == 0){if(!empty($data)){$url .= '?';foreach($data as $k=>$v){$url .= $k . '=' . $v . '&';}}}curl_setopt($ch, CURLOPT_URL ,$url);curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3); // 在发起连接前等待的时间,如果设置为0,则无限等待。curl_setopt($ch, CURLOPT_TIMEOUT, 30); // 设置cURL允许执行的最长秒数。设置超时限制防止死循环curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);// 爬取重定向页面curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自动设置Referer,防止盗链curl_setopt($ch, CURLOPT_HEADER, 0); // 显示返回的Header区域内容curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// 要求结果保存到字符串中还是输出到屏幕上curl_setopt($ch, CURLOPT_USERAGENT, 'Data');// 在HTTP请求中包含一个"User-Agent: "头的字符串。curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // 强制使用 HTTP/1.1if($is_post == 1){curl_setopt($ch, CURLOPT_POST, 1); // 这个请求是postcurl_setopt($ch, CURLOPT_POSTFIELDS , $data);}$html = curl_exec($ch); // 去执行curl,并且打印出来,但是如果关闭了,就不会打印出来if(curl_errno($ch)){return curl_errno($ch);}curl_close($ch);return $html;}header( 'Content-Type:application/json' );//请求头,返回的数据格式//准备好key和数据$data = ['key' => 'b4bae7656b473402175550b','city' => '合肥'];$get_url = get_url('http://apis.juhe.cn/simpleWeather/query',$data);//调用函数$arr = json_decode($get_url,true);//把返回的json数据转为数组print_r($arr);
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号