[已解决] 如何读取 Guzzle 的 Response 响应结果中的 JSON 数据?

使用 [Guzzle](https://github.com/guzzle/guzzle) 时出现的一个问题:

$client = new \GuzzleHttp\Client();

# 获取一个外部 API 接口:
$response = $client->get('http://api.map.baidu.com/geocoder/v2/?callback=renderReverse&location=39.87186,116.479723&output=json&pois=1&ak=Your_AK');

# echo 结果
echo $response->getBody();

输出结果:

renderReverse&&renderReverse({"status":0,"result":{"location":{"lng":116.47972299999994,"lat":39.87186008036971},"formatted_address":"北京市朝阳区西燕东街","business":"十八里店,南磨房,潘家园"c869","zip":""}}})

目前有个疑问,因为现在 Respone 好像使用了 PSR-7 stream objects,不太理解我现在要使用 json 数据的话,如要如何去读取?


直接

json_decode($response->getBody());

个人加了调用 callback,忘记处理了,所以一直无法解析 json 数据

Remote. Open. Engineer.
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2
Ryan

json_decode($response->getBody()->getContents(), true)

7年前 评论
\Guzzle\json_decode( (string) $response->getBody(), true);
\Guzzle\json_decode( $response->getbody()->getContents(), true);
\Guzzle\json_decode( $response->getbody()->__toString(), true);
6年前 评论
Ryan

json_decode($response->getBody()->getContents(), true)

7年前 评论
\Guzzle\json_decode( (string) $response->getBody(), true);
\Guzzle\json_decode( $response->getbody()->getContents(), true);
\Guzzle\json_decode( $response->getbody()->__toString(), true);
6年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!