php获取api接口数据的方法

1、get方式请求api接口

file_get_contents函数

$a = file_get_contents(“http://www.a.com”);

如果接口返回json格式的数据,则要转为数组 r e = j s o n d e c o d e ( re = json_decode( a,true);

2、 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)

3、curl扩展函数也用于get方式请求数据

查看curl是否安装,phpinfo():

在这里插入图片描述

发布了29 篇原创文章 · 获赞 22 · 访问量 2150

猜你喜欢

转载自blog.csdn.net/qq_44476335/article/details/103661872