JordanBelf
JordanBelf

Reputation: 3338

Empty result when parsing a JSON

This is the kind of question I hate asking because I know the answer must be super easy, but I can't seem to figure it out.

I am trying to parse the JSON response from the Stack Exchange API but I am getting an empty string as a result even though I checked the URL and also the JSON formatting and everything seems to be valid.

The code I am using is simply:

$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=stackoverflow");

$json1 = json_decode($surl,true);

print_r($json1);

When I try to echo the content of $surl before json_decode I get a strange response full of characters.

Any tip in the right direction will be appreciated.

Upvotes: 1

Views: 77

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270687

The string returned by the API call, according to the Stack Exchange API documentation has been compressed.

Additionally, all API responses are compressed. The Content-Encoding header is always set, but some proxies will strip this out. The proper way to decode API responses can be found here.

You will need to decompress the string first with gzdecode() and then you'll be able to properly json_decode() it as you tried.

$surl = file_get_contents("https://api.stackexchange.com/2.2/search?order=desc&sort=relevance&intitle=books&site=stackoverflow");

// Decode the compressed string
$surl = gzdecode($surl);

// Then you'll be able to json_decode() it...
$json1 = json_decode($surl, true);

print_r($json1);
// Prints:

Array
(
    [items] => Array
        (
            [0] => Array
                (
                    [tags] => Array
                        (
                            [0] => research
                        )

                    [owner] => Array
                        (
                            [reputation] => 9995
                            [user_id] => 1944
                            [user_type] => registered
                            [accept_rate] => 93
                            [profile_image] => https://www.gravatar.com/avatar/93fc84c261cdce2e2f1d64c8e531ecb7?s=128&d=identicon&r=PG
                            [display_name] => Charles Roper

Upvotes: 3

Related Questions