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