如何在控制器功能中调用API

时间:2017-04-30 09:49:57

标签: php laravel get

我在控制器中有一个函数,我想在AJAX中调用一个像GET请求一样传递url的HTTP请求,但是我无法想象如何使用php我尝试使用它

public function sendAPIRequest()
{
    $url = "https://myapi.com?apikey=".$api."&message=".$message."&receiver=".$receiver;
    //This is what I tried
    file_get_contents($url);
    //But it didn't work
}

1 个答案:

答案 0 :(得分:1)

您可以将Guzzle Package用于Laravel,Guzzle PHP

    $client = new \GuzzleHttp\Client();
$res = $client->request('GET', "https://myapi.com?apikey=".$api."&message=".$message."&receiver=".$receiver);
echo $res->getStatusCode();
// 200
echo $res->getHeaderLine('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// '{"id": 1420053, "name": "guzzle", ...}'