简体   繁体   中英

PHP/Laravel Take json from string

I call an API and the response is like this:

HTTP/1.1 201 Created 
Date: Tue, 12 Jun 2018 13:13:34 GMT
Server: Apache/2.4.x (Ubuntu)
Set-Cookie: PHPSESSID=id; path=/; HttpOnly
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Content-Length: 114
Connection: close
Content-Type: application/json

{"id":"id_code|id_code|id_code","error":{"code":0,"message":"message"}}

What I want to do is take only the json part from final:

{"id":"id_code|id_code|id_code","error":{"code":0,"message":"message"}}

Can I do this using PHP?

Thank you!

You can get the contents of the response with $response->getBody()->getContent() , or you can cast the body to a string. From there if it is in JSON format you can decode it as normal:

// this works
$jsonResults = json_decode($response->getBody()->getContent(), true);

// so does this
$jsonResults = json_decode((string) $response->getBody(), true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM