Saurabh Verma
Saurabh Verma

Reputation: 129

convert response retuned by Guzzle client into json array

$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"
]

I am unable to convert it into proper json. I am unable to access value against login key in the returned PHP stream. I m also unable to convert it into json. How can I access it? I have tried:

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

but it is not valid.

Upvotes: 1

Views: 2865

Answers (1)

Alexey Shokov
Alexey Shokov

Reputation: 5010

You have to call ->getContents() or cast the body to string.

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

Upvotes: 2

Related Questions