usumoio usumoio - 29 days ago 17
PHP Question

PHP Curl request to Stackoverflow API

I'm trying to use

$curl
in PHP to access the stackoverflow api to get the basic info back. I have review the docs and I've tried about a hundred combinations of header and
curl_setopt
commands and nothing will return correctly. Has anyone used curl in PHP to access the stackoverflow API? What parameters did you use to accomplish this?

This is my work as it stands now, note that you can see the commented out work for combinations of curl requests I have tried:

$stack_url = 'https://api.stackexchange.com/2.2/info?site=stackoverflow&key=';

$header[] = "Accept:application/json";
// $header[] = "Accept-Encoding:gzip, deflate";
// $header[] = "Cache-Control:cache";
// $header[] = "Cache-Control:no-cache";
// $header[] = "Accept-Language:en-US,en;q=0.5";
$header[] = "Content-Length: 1000";
$header[] = "Content-Type:application/json";
// $header[] = "Cookie:23";
// $header[] = "X-Requested-With:XMLHttpRequest";

// here we curl request to amazon no matter what
$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $stack_url);

// the needed settings for this curl request
// curl_setopt( $curl, CURLOPT_HEADER, 1 );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $curl, CURLOPT_HTTPHEADER, $header);
// curl_setopt( $curl, CURLOPT_POSTFIELDS, array());
// curl_setopt( $curl, CURLOPT_BINARYTRANSFER, 1 );
// curl_setopt( $curl, CURLOPT_POST, 1 );


$string = curl_exec( $curl );

curl_close( $curl );

debug( $string );
exit;


Right now this work is returning
FALSE
, but I have also returned a 400 bad request for various reasons. I think I've overcame that, but I'm not sure what to do to get the data response back.

Answer

It looks like you are most of the way there, although I don't think any of the headers you have are required. The main thing that is missing is setting the encoding, since all responses are compressed (see the General section of the doco).

This is a quick working example:

<?php

$stack_url = 'https://api.stackexchange.com/2.2/info?site=stackoverflow';

$string  = curl_init($stack_url);

curl_setopt($string, CURLOPT_ENCODING, 'gzip');  // Required by API
curl_setopt($string, CURLOPT_RETURNTRANSFER, 1 );

$result   = curl_exec($string );
curl_close($string );

var_dump($result );

If you are doing a bit more work with the API, you may want to look at a library to manage most of the work like Stack.PHP