API数据接口连接
如何接入API:
protected function http_request($url,$params=false,$ispost=0){try{$httpInfo = array();$ch = curl_init();curl_setopt( $ch, CURLOPT_HTTP_VERSION , CURL_HTTP_VERSION_1_1 );curl_setopt( $ch, CURLOPT_USERAGENT , 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22' );curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT , 30 );curl_setopt( $ch, CURLOPT_TIMEOUT , 30);curl_setopt( $ch, CURLOPT_RETURNTRANSFER , true );if( $ispost ){curl_setopt( $ch , CURLOPT_POST , true );curl_setopt( $ch , CURLOPT_POSTFIELDS , $params );curl_setopt( $ch , CURLOPT_URL , $url );}else{if($params){curl_setopt( $ch , CURLOPT_URL , $url.'?'.$params );}else{curl_setopt( $ch , CURLOPT_URL , $url);}}$response = curl_exec( $ch );$httpCode = curl_getinfo( $ch , CURLINFO_HTTP_CODE );$httpInfo = array_merge( $httpInfo , curl_getinfo( $ch ) );curl_close( $ch );return $response;}catch(\Exception $e){return false;} }通過這個方法接入后,通過接入url地址獲得自己想要的數據,
public function history(){$url="http://apis.juhe.cn/lottery/history";//歷史查詢url地址$params["key"]="84b252036374157d238c097fb8ed1ef0";//key$params["lottery_id"]="ssq";//id為雙色球$params["page_size"]=10;//默認條數是10條$param=http_build_query($params);$result = $this->http_request($url,$param);$res = json_decode($result,true);//返回的是整個json數據 // dump($res); // dump($res['result']['lotteryResList']);die;$list = $res['result']['lotteryResList'];//根據dump出來的數據拆分['result']['lotteryResList']獲得自己需要使用的二維數組$this->assign("list",$list);//注冊變量list$this->show();//顯示在頁面}上面是歷史查詢的url接口,根據請求參數說明,必填key ? lottery_id參數設置號,獲得的list;
res數組是
res下的lotteryResList數組如下是獲得的二維數組;拿到前端頁面循環遍歷list數組
轉載于:https://www.cnblogs.com/forqiwen/p/8776880.html
總結
- 上一篇: JAVA框架Struts2
- 下一篇: XML(二)