使用 Laravel 从 API 获取 JSON 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24936069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting the JSON reponse from an API with Laravel
提问by dabadaba
I am just messing with APIs and now I'm trying to use Google Directions APIin my app.
我只是在搞 API,现在我正在尝试在我的应用程序中使用Google Directions API。
I made a form to get the user's input and retrieve this data and create the URI just in the routes.php
file:
我制作了一个表单来获取用户的输入并检索此数据并仅在routes.php
文件中创建 URI :
Route::get('/directions', function() {
$origin = Input::get('origin');
$destination = Input::get('destination');
$url = "http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false";
});
That URL's response is a JSON. But now, how am I supposed to store that response with Laravel? I have been looking at the Http namespace in Laravel and I didn't find a way. If it can't be done with Laravel, how can it be done with plain php?
该 URL 的响应是一个 JSON。但是现在,我应该如何使用 Laravel 存储该响应?我一直在看 Laravel 中的 Http 命名空间,但没有找到方法。如果用 Laravel 做不到,那用普通的 php 怎么做?
回答by Laurence
You can use file_get_contents()
您可以使用file_get_contents()
Route::get('/directions', function() {
$origin = Input::get('origin');
$destination = Input::get('destination');
$url = urlencode ("http://maps.googleapis.com/maps/api/directions/json?origin=" . $origin . "&destination=" . $destination . "&sensor=false");
$json = json_decode(file_get_contents($url), true);
dd($json);
});
回答by joshuahornby10
Take a look at my package
看看我的包裹
https://github.com/joshhornby/Http
https://github.com/joshhornby/Http
Hopefully makes it a little easier to call APIs
希望让调用 API 更容易一些