将Guzzle客户端重新调整的响应转换为json数组

时间:2017-09-19 16:55:08

标签: php json guzzle6

$repo=new \GuzzleHttp\Client(['headers' =>['Accept'     => 'application/json',
                   'Content-Type'     => 'application/json',
                   'Authorization'  => 'Bearer '.$token,
                ]);
$promise = $repo->get('https://api.github.com/user');
$results = json_decode((string)$promise->getBody(),true);




array:30 [
  "login" => "Saurabh0707"
  "id" => 21239898
  "avatar_url" => "https://avatars2.githubusercontent.com/u/21239898?v=4"
  "gravatar_id" => ""
  "url" => "https://api.github.com/users/Saurabh0707"
  "html_url" => "https://github.com/Saurabh0707"
  "followers_url" => "https://api.github.com/users/Saurabh0707/followers"
  "following_url" => "https://api.github.com/users/Saurabh0707/following{/other_user}"
  "gists_url" => "https://api.github.com/users/Saurabh0707/gists{/gist_id}"
  "starred_url" => "https://api.github.com/users/Saurabh0707/starred{/owner}{/repo}"
  "subscriptions_url" => "https://api.github.com/users/Saurabh0707/subscriptions"
  "organizations_url" => "https://api.github.com/users/Saurabh0707/orgs"
  "repos_url" => "https://api.github.com/users/Saurabh0707/repos"
  "events_url" => "https://api.github.com/users/Saurabh0707/events{/privacy}"
  "received_events_url" => "https://api.github.com/users/Saurabh0707/received_events"
  "type" => "User"
  "site_admin" => false
  "name" => "Saurabh Verma"
  "company" => "Software-Incubator"
  "blog" => "https://github.com/orgs/Software-Incubator/dashboard"
  "location" => "Ghaziabad, India"
  "email" => null
  "hireable" => null
  "bio" => null
  "public_repos" => 6
  "public_gists" => 0
  "followers" => 0
  "following" => 0
  "created_at" => "2016-08-25T11:01:02Z"
  "updated_at" => "2017-09-11T03:35:05Z"
]

我无法将其转换为适当的json。 我无法在返回的PHP流中访问登录密钥的值。我也无法将其转换为json。 我该如何访问它? 我试过了:

$results = json_decode((string)$promise['login]->getBody(),true);

但无效。

1 个答案:

答案 0 :(得分:0)

您必须致电->getContents()或将正文投射到字符串。

json_decode($promise->getBody()->getContents(),true);