使用 guzzle laravel4 从外部 api 获取数据

Get data from external api using guzzle laravel4

我正在尝试使用 laravel 4 中的 Guzzle 4.0 从外部 API 获取数据。

我试过了

$client = new \GuzzleHttp\Client();
$response = $client->get('https://openexchangerates.org/api/latest.json?app_id=************');
echo "<pre>";
dd($response->getBody());

它给了我 Guzzle 对象而不是 JSON 响应,我在浏览器中直接点击了 url,它给出了正确的 json数据.

我得到的回应是:

object(GuzzleHttp\Stream\Stream)#151 (6) {
["stream":"GuzzleHttp\Stream\Stream":private]=>
resource(6) of type (stream)
["size":"GuzzleHttp\Stream\Stream":private]=>
NULL
["seekable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["readable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["writable":"GuzzleHttp\Stream\Stream":private]=>
bool(true)
["uri":"GuzzleHttp\Stream\Stream":private]=>
string(10) "php://temp"
}

谁能告诉我如何获得正确的 json 数据。

在此先感谢您的支持。

尝试将正文转换为字符串:

dd((string) $response->getBody());

getBody() 方法实际上 return 一个对象,这是设计使然。如果您尝试将其用作字符串,它会自动转换为字符串,例如 echo.

虽然在您的 dd() 调用中,您需要显式转换为字符串,否则您将获得对象输出。

这是来自文档:

The body of a response can be retrieved using the getBody method. The body can be used as a string, cast to a string, or used as a stream like object.

$body = $response->getBody();
// Implicitly cast the body to a string and echo it
echo $body;
// Explicitly cast the body to a string
$stringBody = (string) $body;

详情请看这里:

http://docs.guzzlephp.org/en/latest/quickstart.html#using-responses

如果您的响应确实是 JSON,您可以调用响应对象的 json() 方法到 return 一个 JSON 数组。

print_r($response->json());

这在一次调用中完成了转换和解析,我觉得这样更简洁。