简体   繁体   中英

Guzzle HTTP, can't parse response to JSON

So I'm integrating an API from a 3rd party company and I'm facing this strange situation.

I fetch the endpoint with the following code

$client = $this->client = new Client([
    'base_uri' => 'https://xxx.xxxxxxxxxx.com/api/',
    'timeout' => 15
]);

$this->requestConfig = [
    'auth' => [
        'xxxx@xx.xxx',
        'xxxxx'
    ],
    'headers' => [
        'cache-control' => 'no-cache',
        'content-type' => 'application/x-www-form-urlencoded'
    ],

];

$response = $this->client->get($url, $this->requestConfig);

$content = $response->getBody()->getContents();

Now the fun comes, if I var_dump content I get:

string(66) ""[{\"ExternalId\":\"38\",\"AgencyReference\":\"45436070356676\"}]""

Now I know this response is bad, response type if not set a json, json is URL encoded and everything smells bad.

I've been trying to parse this string for a while.

urldecode doesn't work either.

Question is simple, given a response like that, how can I get a normal array?

Currently using PHP 7.1

So finally found this: Remove backslash \\ from string using preg replace of php

To solve my issue.

In this case it was that the escaped quotes where malforming the json. My final code looks like this.

$response = $response->getBody()->getContents();
$clean = stripslashes($response);
$clean = substr($clean, 1, -1);

dd(json_decode($clean));

Please never write your API's like this...

Just looks awfull

BTW, Content-Type makes sense when you send (in request or response) some content. But you send a GET request, that has no content.

And to specify preferred content type for the response, you should use Accept HTTP header, Accept: application/json for example.

I'm not sure this will solve your problem, but just make things clear and correct ;)

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