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

时间:2015-09-08 13:10:44

标签: php laravel guzzle

我正在尝试使用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响应,我直接在浏览器中点击了那个提供正确json数据的URL。

我通过guzzle得到的回应:

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数据。

提前感谢您的支持。

2 个答案:

答案 0 :(得分:2)

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

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

getBody()方法实际上确实返回了一个对象,这是设计的。如果您尝试将其用作字符串,则会自动转换为字符串,例如echo

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

这是来自文档:

  

可以使用getBody方法检索响应的主体。正文可以用作字符串,强制转换为字符串,也可以像对象一样用作流。

$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

答案 1 :(得分:2)

如果您的响应确实是JSON,则可以在响应对象上调用json()方法以返回JSON数组。

print_r($response->json());

这可以在一次通话中进行演员和解析,我觉得它更清洁。