如何在laravel刀片中返回GitHub api

问题描述 投票:0回答:2

如果您访问任何用户https://api.github.com/users/{USERNAME}/repos的github api,您将找到该用户列出的所有存储库,现在我想在我的刀片中循环这个存储库,但我不能。

我尝试过上面分享的简单网址,以及json_decode,但没有运气。

one

知道如何循环这样的数据吗?

laravel
2个回答
3
投票

如果您使用Guzzle来调用API(我无法评论清晰度),您可以像这样获得调用的结果(其中$ response是您的调用值):

$response = json_decode($response->getBody()->getContents());

然后传递给视图:

return view('view')->with(compact('response'));

然后用刀片循环:

   @foreach ($response as $results)
     // do something
   @endforeach

如果对象不是您想要使用的对象,可以通过将true的第二个参数传递给json_decode()函数将这些结果转换为数组

希望有帮助,但如果不是让我知道:)

如果您的申请中没有Guzzle:

1 - 使用Composer将依赖项拉入应用程序

composer require guzzlehttp/guzzle

2 - 在控制器中实例化Guzzle,它将调用Github API并发出GET请求:

$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/users/{USERNAME}/repos');

3 - 访问结果:

$response = json_decode($response->getBody()->getContents());

来自Guzzle Docs的信息:http://docs.guzzlephp.org/en/stable/


0
投票

Solved

我正在使用此代码,现在没有问题

// We make the actuall curl initialization
$ch = curl_init(MY_REPOS_API_URL);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

// We set the right headers: any user agent type, and then the custom token header part that we generated
curl_setopt($ch, CURLOPT_HTTPHEADER, array('User-Agent: Awesome-Octocat-App'));

// We execute the curl
$output = curl_exec($ch);

// And we make sure we close the curl
curl_close($ch);

// Then we decode the output and we could do whatever we want with it
$output = json_decode($output);

Source

© www.soinside.com 2019 - 2024. All rights reserved.