寫網頁程序時,經常要調用api接口獲取數據,本文介紹php獲取api接口數據的方法
get方式請求api接口
file_get_contents函數
$a = file_get_contents("http://www.a.com");
如果接口返回json格式的數據,則要轉為數組$re = json_decode($a,true);
post方式請求接口
curl擴展函數
function request_by_curl($remote_server,$post_string,$use_post=true){ if(function_exists('curl_init')){ $ch = curl_init(); curl_setopt($ch,CURLOPT_URL,$remote_server); if($use_post){ curl_setopt($ch,CURLOPT_POST, 1); curl_setopt($ch,CURLOPT_POSTFIELDS,$post_string); } curl_setopt($ch,CURLOPT_RETURNTRANSFER,true); $data = curl_exec($ch); curl_close($ch); return $data; }else{ return '請先安裝curl'; }}
$post_string為數組,如array("a"=>1)
curl擴展函數也用於get方式請求數據
查看curl是否安裝,phpinfo()
