php獲取api接口數據的方法


寫網頁程序時,經常要調用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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM