1

I have the following URL:

https://api.stackexchange.com/2.0/questions?page=1&pagesize=30&order=desc&sort=activity&site=stackoverflow

When I type this URL in my browser's address bar, it gives me a JSON response, which I need in PHP. I tried using cURL to fetch it (see below code), but it didn't work — no response is printed on the page.

function get_json($url) {
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);
    $resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    if ($resultCode == 200) {
        return json_decode($data);
    } else {
        return false;
    }
}

$json = get_json('https://api.stackexchange.com/2.0/questions?page=1&pagesize=30&
  key=VVq3kJHSjQ*7qgpiRaVoLA%28%28&site=stackoverflow');
echo '<pre>';
print_r($json);

How can I fetch this URL and convert it into a PHP array the right way?

Ry-
  • 218,210
  • 55
  • 464
  • 476
way2project
  • 99
  • 3
  • 8

3 Answers3

3

Last I checked, all responses from the API were gzip'd:

$ch = curl_init();
curl_setopt_array($ch, array(
    CURLOPT_URL => $url
  , CURLOPT_HEADER => 0
  , CURLOPT_RETURNTRANSFER => 1
  , CURLOPT_ENCODING => 'gzip'
));
$data = curl_exec($ch);
var_dump($data);
var_dump(json_decode($data));

Setting CURLOPT_ENCODING enables automatic un gzip'ing of the response, in addition to sending an Accept-Encoding: gzip in the http request, although sending that header isn't strictly required for this to work.

goat
  • 31,486
  • 7
  • 73
  • 96
1

To return an array, use the second parameter in json_decode and set it to true.

if ($resultCode == 200) {
    return json_decode($data, true);
} else {
    return false;
}
Ry-
  • 218,210
  • 55
  • 464
  • 476
Matt Dodge
  • 10,833
  • 7
  • 38
  • 58
0

Try this:

$json = json_decode(file_get_contents("https://api.stackexchange.com/.............."));
echo "<pre>";
print_r($json);
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592